5

I am using NativeBase with React Native.

NativeBase buttons created this way:

    <Button warning>
        <Text>Hello</Text>
    </Button>

Instead of warning you can use different types, such as info or success.

Now, I want to create those buttons based on a prop and trying to do something like this:

<Button {this.props.type}>
    <Text>Hello</Text>
</Button>

But I cannot find a way to do it because this prop does not have a value.

Is it possible to pass props without a value?

boygs
  • 53
  • 3

1 Answers1

6

Component props that can be passed without value are basically boolean props and are resolved as true.

These two are equal:

<Button primary />
<Button primary={true} />

Considering above, you can make use of spread attribute syntax:

<Button {...{ [this.props.type]: true }}>
    <Text>Hello</Text>
</Button>

EDIT (detailed explanation):

Let's say your this.props.type is "success", Button element would resolve to this (because of usage of dynamic property name):

<Button {...{ success: true }}>

Now when you destruct object (these three dots), you'll get all of its properties and corresponding values as element's props:

<Button success={true} >

As I've already mentioned, please take a look at this explanation.

mraaroncruz
  • 3,760
  • 1
  • 30
  • 31
zhuber
  • 5,104
  • 3
  • 28
  • 56
  • Thank you, it works. Could you please explain why it works? I am not sure I fully understand this. – boygs Sep 07 '19 at 09:58