0

I have an element defined as class, and in the render() method I'm trying to give an element a custom attribute data-activates with an id. However, in the resulting html I just see the plaintext of the expression, either one of the following:

data-activates="{this.state._id}"

data-activates="${this.state._id}"

data-activates="{id}"

data-activates="${id}"

The id is present in both props and state, and outside of the element both of them work correctly:

<a className="dropdown-button waves-effect" href="#!" data-activates="{id}">

{ id }, {this.state._id} <- works here

</a>

For some reason React doesn't resolve expressions within the attribute and I need that for the dropdown to work. What am I doing wrong?

Bonus point for a better way to implement dropdown in React, if there is no way to make this code work.

4 Answers 4

3

You have to go into JavaScript land inside your JSX with the help of {}. That way you can use any expression you like in the JSX.

Example

<a
  className="dropdown-button waves-effect"
  href="#"
  data-activates={this.state._id}
>
  Test
</a>
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, the quotes were excessive, the working variant is: ` data-activates={'post_dropdown_'+id}` in my case. Thanks!
1

You should not wrap data attributes inside QUOTES

data-activates={this.state._id}
data-activates={id}

This documentation clears everything check the documentation

Comments

0

Make sure you have tried the following:

<a data-activates={this.state._id}>...</a>
<a data-activates={id}>...</a>

Please bear in mind that JSX adheres to JS syntax first. So inside the curly brackets, you still can do interpolation within tildes (`):

<a data-activates={`my-id-${id}`}>...</a>

Cheers,

Comments

0

Don't use a dash. Use lowerCamelCase instead. React doesn't recognize elements with a dash in the name as a prop. So, instead of data-activates={id}, use dataActivates={id}.

2 Comments

Wrong, React will parse that into meaningless dataactivates=, without the dash. This attribute is an exception that doesn't follow the camelCase.
Sorry. When you said "define element" I thought you mean you were creating a custom component.

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.