Reputation: 116
Hope you can clarify this issue:
I have parent component:
function App() {
const [ thanks, setThanks ] = useState(null);
const thankerHandler=(value)=>{
setThanks(value)
}
**//in the return**
<Route component={PaymentPage} thankerHandler={thankerHandler} path="/payment" />```
and the child component :
const PaymentPage=({thankerHandler})=> {
const [thanks, setThanks] = useState(false);
**//after some logic**
useEffect(() => {
thankerHandler(thanks);
}, [thanks])
the problem is that react is telling me the following:
61 | useEffect(() => {
62 |
> 63 | thankerHandler(thanks);
64 |
65 | }, [thanks])
thankerHandler is not a function
I have no idea what I am doing wrong here, the idea is that when the function will be called in the child component, it will update the value in the parent, but it is not doing the thing, when I console log thankerHandler, just gives me the value of undefined because of the null state in the parent, if I set it there to false, gives me false and so on, but it does not recongnices it as a function.
anyone knows what I am doing wrong here? thanks in advance
Upvotes: 1
Views: 215
Reputation: 29282
Since PaymentPage
component is rendered via Route
component, props
passed to Route
component are not passed to the PaymentPage
component.
Instead of using component
prop to render the PaymentPage
component, use render
prop which takes a function. It will allow you to pass the props
to PaymentPage
component
Change
<Route component={PaymentPage} thankerHandler={thankerHandler} path="/payment" />
to
<Route
path="/payment"
render={(routerProps) => <PaymentPage {...routerProps} thankerHandler={thankerHandler} />}
/>
Apart from this problem, there is another problem in PaymentPage
component.
Since useEffect
is calling the thankerHandler
function, thankerHandler
should be added to the dependency array of the useEffect
hook
useEffect(() => {
thankerHandler(thanks);
}, [thanks, thankerHandler]);
but adding thankerHandler
to the dependency array of useEffect
hook will cause another problem, i.e. when App
component re-renders, thankerHandler
function will be re-created and the reference to this new function will be passed to PaymentPage
component which will cause the useEffect
hook in PaymentPage
component to run again. This may or may not be something you want. If you don't want this, make sure to wrap thankerHanlder
function in useCallback
hook to prevent useEffect
hook from running unnecessarily.
Upvotes: 3
Reputation: 768
try to use render method in Route
component:
<Route render={() => <PaymentPage thankerHandler={thankerHandler} />} path="/payment" />
Upvotes: 0