Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set attribute key (e.g. data-{foo}="bar") in React

Setting an attribute in React is straightforward if you know the key, e.g.

data-500={this.props.YDistance}

but how can one dynamically set part of the key. e.g.

data-{this.props.YDistance}="valueHere"

var Test = React.createClass({

    render: function() {
        return (
            <div data-{this.props.YDistance}="valueHere">
                {this.props.children}
            </div>
        );
    }

});

ReactDOM.render(
    <Test YDistance="500">Hello World!</Test>,
    document.getElementById('container')
);

There are libraries that require this kind of attribute setting (e.g. skrollr et al)

like image 874
Ed Williams Avatar asked Dec 25 '22 05:12

Ed Williams


1 Answers

You could use an object to store the dynamic properties and then use JSX spread attributes.

https://facebook.github.io/react/docs/jsx-spread.html

const propBag = { [`data-${foo}`] = 'bar' };
return (
  <div {...propBag}>
     {this.props.children}
  </div>
);

That is using the computed properties feature of ES6 as well as template literal strings. If you are not using ES6 features you could do an ES5 implementation like so:

var propBag = {};
propBag['data-' + foo] = 'bar';
return (
  <div {...propBag}>
     {this.props.children}
  </div>
);
like image 103
ctrlplusb Avatar answered Dec 28 '22 13:12

ctrlplusb