5

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)

Ed Williams
  • 2,447
  • 3
  • 15
  • 21

1 Answers1

10

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>
);
ctrlplusb
  • 12,847
  • 6
  • 55
  • 57
  • 1
    This can be further simplified inline with [computed keys](http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer): `
    ...
    `.
    – Yuya Jun 07 '16 at 13:32
  • Thanks @ctrlplusb - great solution! Small edit... should the first line read `const propBag = { [`data-${foo}`] : 'bar' };` ? – Ed Williams Jun 07 '16 at 13:54
  • No problem. :) It's not a typo no. Look into those links that I provided underneath the code example. It's some magic ES6 syntax being used. Don't worry, it's not too magic, if you go through a couple of examples you'll quickly grasp them. :) – ctrlplusb Jun 07 '16 at 13:56
  • @EdWilliams You are right, but you don't need even square bracket: `const propBag = { \`data-${foo}\`: 'bar' };` is a valid syntax! – Csaba Toth Jul 14 '16 at 20:35
  • i am storing attributes into the object and then using spread operator but its giving unexpected token issue for this.state.atributes – CyberAbhay Aug 16 '18 at 09:28