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

2 Answers2

7

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,780
  • 2
  • 32
  • 31
zhuber
  • 5,364
  • 3
  • 30
  • 63
  • 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
0

Yes, it possible to pass props without a value. If you do this then a boolean value true will be passed. Otherwise if you want to pass false as a boolean value then mention explicitly like warning={false}.

raj
  • 21
  • 3