Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  26] [ 4]  / answers: 1 / hits: 148433  / 9 Years ago, tue, july 7, 2015, 12:00:00

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


More From » html

 Answers
165

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


[#65900] Saturday, July 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;