Joe
Joe

Reputation: 4234

React, Conditionally send props to Component

const Comp = ({noValue, value}) => (
  <Slider value={value}>
)

Is there any way to not send the value-property based on a condition (noValue)?

So if noValue = true: < Slider />

if noValue = false: < Slider value={value} />

<Slider /> is an external lib and it crashes if I do value={null}

Upvotes: 1

Views: 66

Answers (4)

vitomadio
vitomadio

Reputation: 1140

You can do it as follows:

const Comp = ({value}) => (
    value ?
   <Slider value={value}> 
   :
   <Slider />
)

This should help.

Upvotes: 0

Marc Sloth Eastman
Marc Sloth Eastman

Reputation: 801

Above answers are good too, just wanted to show some alternate syntax

const Comp = ({noValue, value}) => {
  const props = noValue ? {} : {value: value};
  return <Slider {...props}>
}

Upvotes: 2

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

You can do this way

  const Comp = ({noValue, value}) => (
     <Slider value={noValue ? null : value} />
  )

Or

const Comp = ({noValue, value}) => {
     if(noValue){
        return <Slider />
     }
     return <Slider value={value}>
}

Upvotes: 1

Tholle
Tholle

Reputation: 112787

You can pass undefined as the value prop if noValue is true.

const Comp = ({ noValue, value }) => (
  <Slider value={noValue ? undefined : value} />
)

Upvotes: 1

Related Questions