Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Pass prop without a value

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?

like image 794
boygs Avatar asked Sep 07 '19 09:09

boygs


1 Answers

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.

like image 139
zhuber Avatar answered Sep 30 '22 14:09

zhuber