'React callback function does not work how to fix it?
On one of my react Components I need to use a callback function. The the construction of my site is like this:
<Mainview >
<Header />
<Main />
<Footer />
</Mainview>
In one of my Main Component I used this:
const Produkt = (produkt, { zumWarenkorbHinzufuegen }) => {
return (
<main>
// ...
<input
type="button"
value="In den Warenkorb"
id="Knopfwarenkorb1"
onClick={() => { zumWarenkorbHinzufuegen(produkt.id) }} />
// ...
</main>
In the main view I used this :
<Route path="/bambus-zahnbuerste" component={() => <Produkt id={produkt[0].id}
name={produkt[0].name}
bild={produkt[0].bild}
preis={produkt[0].preis}
zumWarenkorbHinzufuegen={zumwarenkorb} />} />
The function "zumwarenkorb" is also defined in the <Mainview />
So when I click the button on my <Produkt /> Component I get the following error:
TypeError: zumWarenkorbHinzufuegen is not a function. (In 'zumWarenkorbHinzufuegen(produkt.id)', 'zumWarenkorbHinzufuegen' is undefined)
Solution 1:[1]
Your component's props are passed through the first argument of the Produkt function, or in your case the produkt argument. To access the value of the zumWarenkorbHinzufuegen prop, you have to unpack it from produkt in the body of your function:
const { zumWarenkorbHinzufuegen } = produkt;
Solution 2:[2]
You can destructure props in Produkt component to get produkt id and zumWarenkorbHinzufuegen function.
const Produkt = ({id, zumWarenkorbHinzufuegen }) => {}
or you can keep the props and use like
const Produkt = (props) => {
...
<input type="button"
value="In den Warenkorb"
id="Knopfwarenkorb1"
onClick={() => { props.zumWarenkorbHinzufuegen(props.id) }}
/>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Altareos |
| Solution 2 | Anuj Verma |
