How does injected JavaScript work within '{ }'?

Viewed 53

In JSX, When we want to add JavaScript between JSX we use '{}', which indicates injected JavaScript. I was wondering how does this work? How does '{}' treats as JavaScript? Is it different than '${}'? Which we use in string interpolation.

3 Answers

JSX is just a syntactic sugar for React.createElement, it transpiled by babel, so you can check how inner scope treated with babel playground:

<div>
  {'Inner Scope'}
</div>

Which transpiled to:

React.createElement("div", null, 'Inner Scope');

That means, the answer to "How does '{}' treats as JavaScript" is by passing the inner scope to React.createElement - children agrument.

React.createElement(
  type,
  [props],
  [...children]
)

They are pretty similar. In JSX, when you're in the middle of writing JSX markup, and the interpreter comes across {someExpression}, it will indeed evaluate someExpression as JavaScript (rather than JSX markup) and either:

  • Interpolate the resulting expression into the markup as a string, if in the context of a React child, eg:

    <div>
    {someExpression}
    </div>
    

    This is exactly the same thing that ${} does inside a template literal. As React docs show:

    <div>Hello {this.props.toWhat}</div>
    

    compiles to

    return React.createElement('div', null, `Hello ${this.props.toWhat}`);
    
  • Or, if in the context of a prop, the expression will be passed as a prop to the component there, eg:

    <div onClick={someExpression}> 
    </div>
    

    This is not interpolation, but it indicates to the compiler to pass the resulting expression as a part of an object, as props. For example:

    <Hello toWhat={SomeExpression} />,
    

    gets compiled to

    React.createElement(Hello, {toWhat: SomeExpression}, null),
    
Related