Search code examples
javascriptreactjsstaterendercustom-attribute

React JS - accessing component property in an element attribute


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.


Solution

  • 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>