Using template literal in jsx doesn't work

Viewed 52

In a React app I want to render

"<td className="RuleRow-name">{{`rulesD.${this.props.name}`}}</td>"

So, if this.props.name is "john" it should render the value of rulesD.john.

I've tried composing the template literal in a few different ways but nothing works.

2 Answers

The result of a template literal is a string, while you are trying to get property name, where name can be any string, for example "john". To do so, use brackets notation to get the value of the prop name in object rulesD:

<td className="RuleRow-name">{rulesD[this.props.name]}</td>

Example

const rulesD = { john: 1, jill: 2 }

const Demo = ({ name }) => (
  <div>{rulesD[name]}</div>
)

ReactDOM.render(
  <div>
    <Demo name="john" />
    <Demo name="jill" />
  </div>,
  root
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

it should be like

<td>{`rulesD.${this.props.name}`}</td>
Related