Search code examples
reactjsconditional-statementsgatsbyrender

Re-render a component in gatsby


I'm using react and I can't find how to conditional render this example in gatsby. The main goal is re-render the child component every time I changes in value but I don't want to re-render all the website only the Child component

import * as React from "react"
    
    let i=1;
    
    const Test = () => {
      return (
        
        <main>
        <button onClick={()=>{i=i+1;console.log(i) }}>CLICK ON ME</button>    
        <Child></Child>
        </main>  
               
                  
            
      )
    }
    
    export default Test
    
    const Child = () => {
        if(i===1){
            return(
            <div >
                1
                </div>
            )
        }
        if(i===2){
            return(
            <div >
                2
                </div>
            )
        }
        if(i===3){
            return(
            <div >
                3
                </div>
            )
        }
        else{
            return(
            <div >
                4+
                </div>
            )
        }
      
      
    
    
    }

Solution

  • Gatsby is a React-based framework, it uses React under the hood so the component and state management is identical to Reacts.

    In your case, try using a useState hook to render the Child, passing the integer as props:

       const Test = () => {
         const [i, setI] = useState(1)
    
          return (
            <main>
            <button onClick={()=>{setI(i+ 1);console.log(i) }}>CLICK ON ME</button>    
            <Child i={i} />
            </main>  
          )
        }
    

    In the Child component:

    const Child = ({ i }) => {
      return <div>{i}</div>
    }
    

    If you want to conditionally render different components depending on i valu, just use:

    const Child = ({ i }) => {
      return <>
      {i==1 && <div>Some rendered content when i==1</div>}
      {i==2 && <div>Some rendered content when i==2</div>}
      </>
    }
    

    React's state management will only rehydrate (render) the needed parts that have changed accordingly. In this case, because you are changing the i value with the setI function, it will rehydrate the child changing the value lifted using props.