How to add custom html attributes in JSX How to add custom html attributes in JSX reactjs reactjs

How to add custom html attributes in JSX


EDIT: Updated to reflect React 16

Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render function, like so:

render() {  return (    <div custom-attribute="some-value" />  );}

For more:
https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes
https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html


Previous answer (React 15 and earlier)

Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140

As a workaround, you can do something like this in componentDidMount:

componentDidMount: function() {  var element = ReactDOM.findDOMNode(this.refs.test);  element.setAttribute('custom-attribute', 'some value');}

See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)


You can add an attribute using ES6 spread operator, e.g.

let myAttr = {'data-attr': 'value'}

and in render method:

<MyComponent {...myAttr} />


Consider you want to pass a custom attribute named myAttr with value myValue, this will work:

<MyComponent data-myAttr={myValue} />