Search code examples
javascriptreactjsconditional-operatorconditional-rendering

Check if props are undefined when loading component


I have a question regarding checking if props are undefined in a functional component in order to render one screen or another.

My functional component:

const InfoHeader = ({population, infected, recovered, deaths, active}) => {
console.log(population)
    return(
        <div className="infoHeader-wrapper">
            ///code to render the information passed into the props
        </div>
    )
}

export default InfoHeader

I know the props on first load are undefined since they only get a value upon user interaction with a section on a map I created.

My question here is:

Rather than doing something like

if(population !==undefined && infected !== undefined && ... )

Is there a better way in order to create a ternary operator to conditionally render one element or another in the functional component' return? Something like:

return(
   allProps !== undefined ?? renderX : renderY
)

Many thanks


Solution

  • you could create a function that takes props that validates all values are not undefined:

    const InfoHeader = (props) => {
      const {population, infected, recovered, deaths, active} = props
    
      const propsValid = (props) => Object.values(props).every(prop => prop !== undefined)
    
      console.log(population)
      return(
        propsValid(props) ? renderX : renderY
      )
    }
    
    export default InfoHeader