Reputation: 141
What is the best way to add a custom attribute to JSX? Facebook say´s its already implemented with React v16.
It is. But if I understand it right, I have to do it like my-custom-attribute="foo"
. Thats not working for me. Because I need a attribute like MyCustomAttribute="foo"
Any Ideas?
Upvotes: 2
Views: 2833
Reputation: 3407
Do like below to add your custom attributes to a component
Expected Parent Component :
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
let selDynamicAttributes = {"data-attr":"someString", "MyCustomAttribute":"foo"}; // see here added custom attrib
return (
<div>
<Button {...selDynamicAttributes} /> //passed custom attributes
</div>
);
}
}
Expected Child Component:
export default class Button extends React.Component {
constructor(props) {
super(props);
}
render(){
const { ...otherAttributes } = this.props;
return(
<div>
<button
{...otherAttributes}>
{this.props.displayText}
</button>
</div>
);
}
}
Read more at : How to add custom html attributes in JSX
Upvotes: 2
Reputation: 57
Are you referring to a component? in javascript you can not use that convection it throws you an error of "Uncaught SyntaxError: Unexpected token -", I recommend you to use snake_case which is the closest thing to your case. but really what I recommend is to always use camelCase.
Upvotes: 0