Search code examples
javascriptreactjsreact-props

How to render another react component on a single button click? (Functional Component)


I am very new to React and I want to render another react component on a single click. I have a component ListModules which has a button in it, now when I click the button another component should get rendered. I have written the below code, module is my state and has value from the backend.

    const addTimeline = () => {
      return <ColorsTimeline data={module} />
      }
     <button type="submit" class="btn btn-success" onClick={addTimeline}>DONE</button>
 

Please help :)


Solution

  • This should work:

    const[show,setShow]=useState(false);
    return(
    {show?<ColorsTimeline data={module} />:null}
    <button type="submit" class="btn btn-success" onClick={()=>{setShow(true)}}>DONE</button>
    )
    

    Edit: if you want to hide the button once it gets clicked? Click the button, call another component and hide button! For example:

    const [showButton,setShowButton]=useState(true);
    return(
      {show?<ColorsTimeline data={module} />:null}
      {showButton?<button type="submit" class="btn btn-success" onClick={()=>{setShow(true);setShowButton(false)}}>DONE</button>:null}
    ) 
    

    or better do this:

    return(
      {show?<ColorsTimeline data={module} />:null}
      {!show?<button type="submit" class="btn btn-success" onClick={()=>{setShow(true)}}>DONE</button>:null}
    )