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?

1
  • It would help to have an example of what you've already tried Commented Feb 27, 2018 at 12:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Nope. I need it for a Universal Windows App. So I have to add an attribute named "IsTabStop" to a <div>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.