How to add custom html attributes in JSX

JavascriptHtmlnode.jsReactjsReact Component

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

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

and in render method:

<MyComponent {...myAttr} />

Solution 3 - Javascript

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

<MyComponent data-myAttr={myValue} />

Solution 4 - Javascript

You can use the "is" attribute to disable the React attribute whitelist for an element.

See my anwser here: Stackoverflow

Solution 5 - Javascript

if you are using es6 this should work:

<input {...{ "customattribute": "somevalue" }} />

Solution 6 - Javascript

I ran into this problem a lot when attempting to use SVG with react.

I ended up using quite a dirty fix, but it's useful to know this option existed. Below I allow the use of the vector-effect attribute on SVG elements.

import SVGDOMPropertyConfig from 'react/lib/SVGDOMPropertyConfig.js';
import DOMProperty from 'react/lib/DOMProperty.js';

SVGDOMPropertyConfig.Properties.vectorEffect = DOMProperty.injection.MUST_USE_ATTRIBUTE;
SVGDOMPropertyConfig.DOMAttributeNames.vectorEffect = 'vector-effect';

As long as this is included/imported before you start using react, it should work.

Solution 7 - Javascript

See attribute value in console on click event

//...
   alertMessage (cEvent){
           console.log(cEvent.target.getAttribute('customEvent')); /*display attribute value */
    	}
//...

simple add customAttribute as your wish in render method

render(){
	return <div>
//..
	<button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
			</div>
		}
//...

Solution 8 - Javascript

Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.

var Hello = React.createClass({
    componentDidMount: function() {
        ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
    },
    render: function() {
        return <div>
            <span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
        </div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Facebook's ref documentation

Solution 9 - Javascript

Depending on what exactly is preventing you from doing this, there's another option that requires no changes to your current implementation. You should be able to augment React in your project with a .ts or .d.ts file (not sure which) at project root. It would look something like this:

declare module 'react' {
    interface HTMLAttributes<T> extends React.DOMAttributes<T> {
        'custom-attribute'?: string; // or 'some-value' | 'another-value'
    }
}

Another possibility is the following:

declare namespace JSX {
    interface IntrinsicElements {
        [elemName: string]: any;
    }
}

See JSX | Type Checking

You might even have to wrap that in a declare global {. I haven't landed on a final solution yet.

See also: https://stackoverflow.com/questions/40093655/how-do-i-add-attributes-to-existing-html-elements-in-typescript-jsx

Solution 10 - Javascript

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

Solution 11 - Javascript

For any custom attributes I use react-any-attr package https://www.npmjs.com/package/react-any-attr

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrey BoriskoView Question on Stackoverflow
Solution 1 - JavascriptpeterjmagView Answer on Stackoverflow
Solution 2 - JavascriptSpadar ShutView Answer on Stackoverflow
Solution 3 - JavascriptLuca FagioliView Answer on Stackoverflow
Solution 4 - JavascriptChristian SteinmannView Answer on Stackoverflow
Solution 5 - JavascriptSquiblyView Answer on Stackoverflow
Solution 6 - JavascriptrbhallaView Answer on Stackoverflow
Solution 7 - JavascriptGMKHussainView Answer on Stackoverflow
Solution 8 - JavascriptDixon MinnickView Answer on Stackoverflow
Solution 9 - JavascriptjedmaoView Answer on Stackoverflow
Solution 10 - JavascriptVaibhav BhatiaView Answer on Stackoverflow
Solution 11 - JavascriptItay MerchavView Answer on Stackoverflow