There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
Consider you want to pass a custom attribute named
myAttr
with valuemyValue
, this will work:You can use the "is" attribute to disable the React attribute whitelist for an element.
See my anwser here: Stackoverflow
You can add an attribute using ES6 spread operator, e.g.
and in render method:
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.
Facebook's ref documentation
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.As long as this is included/imported before you start using react, it should work.
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: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
:See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)