Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 42627  / 7 Years ago, tue, october 17, 2017, 12:00:00

I've seen similar posts but couldn't find an answer and in my case, I'm trying to pass an action from <App />:



  addExpense = (expense) => {
console.log('Hello From AddExpenseForm');
}


to /create route where I'm rendering <AddExpenseForm /> component



<Link to={{
pathname: '/create',
state: { addExpense: this.addExpense }
}}> Create Expense</Link>


The link is rendered but when I click on it I get an error in console:



Uncaught DOMException: Failed to execute 'pushState' on 'History': function (expense) {
console.log('Hello From addExpense');
} could not be cloned


Why is that and what's the workaround here?



My updated code:



Routes in Index.js:



const Routes = () => {
return (
<BrowserRouter>
<Switch>
<Route path=/ exact component={App} />
<Route path=/create exact component={AddExpenseForm}/>
<Route path=/expense/:expenseId name=routename component={ExpenseDetails} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
}


App.js:



  addExpense = (expense = {}) => {
console.log('Hello From AddExpenseForm');
}

goToNextPage = (addExpense) => {
this.props.history.push({
pathname: '/create',
state: { addExpense: this.addExpense }
});
}

render() {
return (
<div>
<Header
/>
<button onClick={this.goToNextPage}>Create</button>
...

More From » reactjs

 Answers
7

Firstly, add some default value to your addExpense function:



  addExpense = (expense = DEFAULT) => {
console.log('Hello From addExpense');
}


Then Use Link:



<Link to={`/ideas/${this.addExpense}`}>Create Expense​</Link>         


OR Try this (Better Approach):



  goToNextPage = (addExpense) => {
this.props.history.push({
pathname: '/create',
state: { addExpense: addExpense }
});
}


In next (create) component use the passed on values like this:



this.props.location.state.addExpense();

[#56201] Saturday, October 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;