3

How can I insert a string of data attributes to a react render function in a simple way?

  render() {
    let data_attr_str=' data-test="1" data-test-2="2"';

    return (
      <div className="grid" {data_attr_str}>
        WHY YOU NOT WORKING? 
      </div>
    );
  }
2
  • Do you want to de-serialize data and show it with JSX? Commented Mar 7, 2018 at 19:33
  • Hey Tiago, I would like the final html output to be: <div class="grid" data-test="1" data-test-2="2"> WHY YOU NOT WORKING?</div> Commented Mar 7, 2018 at 19:35

1 Answer 1

11

JSX is not a template engine, so you can't just concatenate that string. I think you should check https://reactjs.org/docs/jsx-in-depth.html for more details.

But you can use spread attributes: https://reactjs.org/docs/jsx-in-depth.html#spread-attributes.

render() {
  let dataAttrs = {
    'data-test': '1',
    'data-test-2': '2'
  };

  return (
    <div className="grid" {...dataAttrs}>
      NOW IT WORKS
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks fhelwanger , also +1 for the 'NOW IT WORKS!'

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.