'React Conditional Rendering Child
I'm new to React and trying to understand using props with conditional rendering. I have a component called Intro.js inside my app.js.
My goal is to click a button on a form in Intro.js and remove Intro from app.js I've been able to accomplish this with a button in app.js but not within Intro.js. How would I get this to work within the child component Intro.js
const [introSection, setIntroSection] = useState(false)
{
introSection ? <Intro /> : true
}
<Button onClick={() => setIntro(false)}> Remove Intro Section</Button>
Solution 1:[1]
Firstly, your state update is also not aligned with the actual function. It should be setIntroSection instead of setIntro
<Button onClick={() => setIntroSection(false)}> Remove Intro Section</Button>
You're almost there with your logic. You just need to modify your logic like below
{
introSection ? <Intro /> : null
}
<Button onClick={() => setIntroSection(false)}> Remove Intro Section</Button>
But this is not a good way when we have a very complex structure in the true path, so I personally prefer this way
{introSection && <Intro />} //when it's false, nothing is rendered
<Button onClick={() => setIntroSection(false)}> Remove Intro Section</Button>
If you want to do it inside Intro, you can pass a prop
<Intro isHidden={true} />
And in Intro, you can have this logic
const Intro = ({ isHidden }) => {
if(isHidden) {
return null
}
//true path to render your own component
return <div></div>
}
Solution 2:[2]
You should pass your setIntro/setIntroSection (it depends how you used it) function to Intro component as a prop, so then you will be able to access and use that state function. I hope this helps.
Solution 3:[3]
Use setIntroSection, not setIntro.
A whole bunch of code will be helpful to answer.
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 | |
| Solution 2 | dogukyilmaz |
| Solution 3 | Dongjin Kim |
