11

I am adding div to the DOM as below,

React.createElement("div", { className: "test"});

The rendered html should be as below

<div class="test" data-test>
</div>

Where can I add data-test in the createElement?

2 Answers 2

4

If you refer to the doc on createElement API, you can insert the value to your data-test prop like this:

React.createElement('div', {className: 'test', 'data-test': 'some value'});
Sign up to request clarification or add additional context in comments.

2 Comments

There's a syntax error in your code: data-test must be quoted.
@elektronik Good catch! :)
1

You can't do that because attribute without any value means that this attribute has value true in JSX. Just don't pass data-test and this.props['data-test'] will be undefined in your component. Or if you need to have this attribute with empty value then just add it to your default values in component definition.

defaultProps: {
    'data-test': ''
}

2 Comments

Thanks! This solved my issue and allowed my to add an attribute without value to my html tag.

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.