Home > Net >  React Conditional Rendering Child
React Conditional Rendering Child

Time:04-06

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>
            
       

CodePudding user response:

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>
}

CodePudding user response:

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.

CodePudding user response:

Use setIntroSection, not setIntro.

A whole bunch of code will be helpful to answer.

  • Related