Dynamic attribute in ReactJS

The cleanest way to add optional attributes (including disabled and others you might want to use) is currently to use JSX spread attributes:

var Hello = React.createClass({
    render: function() {
        var opts = {};
        if (this.props.disabled) {
            opts['disabled'] = 'disabled';
        }
        return <button {...opts}>Hello {this.props.name}</button>;
    }
});

React.render((<div><Hello name="Disabled" disabled='true' />
    <Hello name="Enabled"  />
</div>)
, document.getElementById('container'));

By using spread attributes, you can dynamically add (or override) whatever attributes you’d like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.

If you only want to use disabled though, this answer works well.

Leave a Comment