Home > database >  Conditionally pick a prop to use
Conditionally pick a prop to use

Time:02-18

const Component = ({

    const someBoolean 

    return (
          <Component
             prop1
             prop2

I want to use prop1 ONLY when someBoolean is true, otherwise prop2 should be used. What is the best way to do this ?

So say someBoolean is true I would have

const Component = ({

    const someBoolean 

    return (
          <Component
             prop1

Otherwise I would have

const Component = ({

    const someBoolean 

    return (
          <Component
             prop2

CodePudding user response:

Best way to do this is with ternary operators. I'm new to React and this I believe is how you can implement conditional rendering

const Component = ({

    const someBoolean 

    return (someboolean ? <Component prop1> : <Component prop2>)
}) 

CodePudding user response:

You can use spread operator.

const Component = ({
    const someBoolean;
    const finalProp = someBoolean ? prop1 : prop2;   

    return (
          <Component {...finalProp} />
    )
})

CodePudding user response:

const Component = ({

    const prop = someBoolean ? prop1 : prop2 

    return (
          <Component
             prop />
})
  • Related