-2

I am new to JSX, and javascript in general, and I am confused by {} having multiple meanings based on what is in and around them. I am confused about the difference between {} and ${} in the following example from the React docs.
In an example explaining hooks, we see <button onClick={() => this.setState({ count: this.state.count + 1 })}>

Here, the innermost curly braces indicate that a JS object with one key: value pair is what is being passed as the sole parameter to this.setState().

Later, in the componentDidUpdate and componentDidMount methods we see document.title = `You clicked ${this.state.count} times/`;

In this snippet, the curly braces do not surround a key: value pair so I know it not a JSON object. It's inside {} in JSX so this.state.count should just evaluate to a number but what is the meaning of the $ in this expression?

Thanks in advance!

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

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

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

2 Answers2

1

In JavaScript content between backticks is a template string and ${...} is the syntax you can use to embed a JavaScript expression inside the template.

In JSX {...} is used to assign a dynamic value (as opposed to a static one) to a prop on a component.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The `` and $ combination is a way to concatenate strings that's easier to read than the old way of using +.

For example say you have obtained the users firstname through some input you might output some string like Hi There Mark! where Mark is the users name. You can do this with either "Hi There" + user.firstname + "!" or `Hi There ${user.firstname}!`.

Mark Potter
  • 302
  • 1
  • 8