2

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?

2 Answers2

2

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>
        );      
    }
}

Working Demo

Read more at : How to add custom html attributes in JSX

Jayavel
  • 3,377
  • 2
  • 21
  • 35
0

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.

Alexis Mateo
  • 57
  • 1
  • 7