Skip to content
Wei edited this page Apr 23, 2019 · 1 revision

Embedding Expressions in JSX

In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces:

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.

Specifying Attributes with JSX

You may use quotes to specify string literals as attributes: const element = <div tabIndex="0"></div>; You may also use curly braces to embed a JavaScript expression in an attribute: const element = <img src={user.avatarUrl}></img>;

  • Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.

Specifying Children with JSX

JSX tags may contain children:

const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

Clone this wiki locally