javascript - props - react: use && for a more concise conditional




How to conditionally add attributes to React components? (8)

Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:

var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }
});

will result in:

<input type="text" required data-reactid=".0.0">

Is there a way to only add attributes to a React component if a certain condition is met?

I'm supposed to add required and readOnly attributes to form elements based on an ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

The example below should explain what I want, but wont work (Parse Error: Unexpected identifier).

var React = require('React');

var MyOwnInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
            </div>
        );
    }
});

module.exports = React.createClass({
    getInitialState: function () {
        return {
            isRequired: false
        }
    },
    componentDidMount: function () {
        this.setState({
            isRequired: true
        });
    },
    render: function () {
        var isRequired = this.state.isRequired;

        return (
            <MyOwnInput name="test" {isRequired ? "required" : ""} />
        );
    }
});

Considering this post JSX In Depth you can solve your problem this way

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);

Here's a way I do it.

with Conditional :

  <Label
    {...{
      text: label,
      type,
      ...(tooltip && { tooltip }),
      isRequired: required
    }}
  />

I still prefer using the regular way of passing props down because it is more readable (in my opinion) in the case of not have any conditionals.

with No conditional :

 <Label text={label} type={type} tooltip={tooltip} isRequired={required} />

If you use es6, you can simply write like this.

// first, create a wrap object.
const wrap = {
    [variableName]: true
}
// then, use it
<SomeComponent {...{wrap}} />

Just throwing another option out there, but @juandemarco's answer is usually correct.

Build an object how you like:

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition) inputProps.disabled = true;

Render with spread, optionally passing other props also.

<input 
    value="this is overridden by inputProps" 
    {...inputProps} 
    onChange={overridesInputProps}
 />

Late to the party.

Lets say we want to add a custom property (using aria-* or data-*) if a condition is true:

{...this.props.isTrue && {'aria-name' : 'something here'}}

Lets say we want to add a style property if a condition is true:

{...this.props.isTrue && {style : {color: 'red'}}}

This should work, since your state will change after the ajax call, and the parent component will re-render.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>    
    );
}

You can use the same shortcut, which is used to add/remove (parts of) components ( {isVisible && <SomeComponent />} ).

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}






reactjs