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)
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>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With