I want to pass the setter of a React Hook to a Child Component. So that a button in the child ponent updates the state via setter which is saved in the Parent Component. I tried following setup but I get an error message :
TypeError: setshowOptionPC is not a function onClick
Is my approach even possible? And if not how could I possibly do that structure using a React Hook.
Below a simplified version of my code:
import React, { useState } from "react";
function ChildComponent({ setshowChildOptionBC, setshowChildOptionPC }) (
<div>
<button
onClick={() => {
setshowChildOptionPC(false);
setshowChildOptionBC(true);
}}
>
BC
</button>
<button
onClick={() => {
setshowChildOptionPC(true);
setshowChildOptionBC(false);
}}
>
PC
</button>
</div>
);
function ParentComponent() {
const [showOptionBC, setshowOptionBC] = useState(true);
const [showOptionPC, setshowOptionPC] = useState(false);
return (
<div>
<ChildComponent
setshowChildOptionBC={setshowOptionBC}
setshowChildOptionPC={setshowOptionPC}
/>
{showOptionBC && <div>BC</div>}
{showOptionPC && <div>PC</div>}
</div>
);
}
export default ParentComponent;
I want to pass the setter of a React Hook to a Child Component. So that a button in the child ponent updates the state via setter which is saved in the Parent Component. I tried following setup but I get an error message :
TypeError: setshowOptionPC is not a function onClick
Is my approach even possible? And if not how could I possibly do that structure using a React Hook.
Below a simplified version of my code:
import React, { useState } from "react";
function ChildComponent({ setshowChildOptionBC, setshowChildOptionPC }) (
<div>
<button
onClick={() => {
setshowChildOptionPC(false);
setshowChildOptionBC(true);
}}
>
BC
</button>
<button
onClick={() => {
setshowChildOptionPC(true);
setshowChildOptionBC(false);
}}
>
PC
</button>
</div>
);
function ParentComponent() {
const [showOptionBC, setshowOptionBC] = useState(true);
const [showOptionPC, setshowOptionPC] = useState(false);
return (
<div>
<ChildComponent
setshowChildOptionBC={setshowOptionBC}
setshowChildOptionPC={setshowOptionPC}
/>
{showOptionBC && <div>BC</div>}
{showOptionPC && <div>PC</div>}
</div>
);
}
export default ParentComponent;
Share
Improve this question
edited Nov 14, 2019 at 17:19
Jurrian
8496 silver badges20 bronze badges
asked Nov 14, 2019 at 15:35
mafehxmafehx
5112 gold badges8 silver badges16 bronze badges
1
-
2
function ChildComponent({ setshowOptionBC, setshowOptionPC })
you’re missing the braces – hackape Commented Nov 14, 2019 at 15:43
1 Answer
Reset to default 5I think you just forgot to destructure props in your child ponent. This might help.
function ChildComponent({setshowOptionBC, setshowOptionPC}) {..