Skip to content
Advertisement

How to add custom html attributes in JSX

There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?

Advertisement

Answer

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.)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement