Alexander Mills
Alexander Mills

Reputation: 100010

Conditionally add/remove property from element with React

I have this TextField element. I want to conditionally add either value={x} or defaultValue={x}

this will work (without any conditionals)

<TextField
    id="pickupName"
    className="order-form-input"
    onBlur={this.fieldChange('name')}
    ref="pickupName"
    defaultValue={(order.pickup || {}).name || ''}
    // hintText="Pickup Contact Name"
    floatingLabelFixed={true}
    floatingLabelText="Contact Name"
/>

however, if I try to add conditionals (of course it will fail):

<TextField
    id="pickupName"
    className="order-form-input"
    onBlur={this.fieldChange('name')}
    ref="pickupName"
      {true ? defaultValue={(order.pickup || {}).name || ''} :
                            value={(order.pickup || {}).name || ''}}
    // hintText="Pickup Contact Name"
    floatingLabelFixed={true}
    floatingLabelText="Contact Name"
/>

is there a way to have the defaultValue or value properties point to functions instead of static strings? Given my need, I have to conditionally use either value or defaultValue because they behave quite differently.

Upvotes: 1

Views: 3018

Answers (1)

Yurii Kramarenko
Yurii Kramarenko

Reputation: 1054

If you are using es6 you parse all remaining arguments in the end of component declaration using {...args} operator.

Example:

<TextField
    id="pickupName"
    className="order-form-input"
    onBlur={this.fieldChange('name')}
    ref="pickupName"
    floatingLabelFixed={true}
    floatingLabelText="Contact Name",
    {...extra_args}
    />

I hope it will work.

Upvotes: 1

Related Questions