Search code examples
javascriptreactjsstringtemplate-literals

why in React can you express a variable inside an html element without using the template literal sintax?


I'm following and reading a bunch of courses on React, but I'm confused, sometimes I see using the template literal notation to express variables inside html elements, such as p and h elements, some other times for the same elements there's no such use. An example of this from the ReactJS documentation:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

Why the expression inside the p tag is not written like this?

<p>`You clicked ${this.state.count} times`</p>

Solution

  • In JSX, JavaScript expressions are always delimited by { } brackets. Eg

    {this.state.count}
    {() => this.setState({ count: this.state.count + 1 })}
    

    Unless you use brackets, you can't use JavaScript expressions - you can only write plain text. That's just how the syntax was designed.

    You could use a template literal for the <p> content if you wanted, but template literals are JS expressions, so you'd need brackets around the whole contents of the <p>:

    <p>{`You clicked ${this.state.count} times`}</p>