Am I always going to use curly braces to write JavaScript inside of JSX?

Question

Am I always going to use curly braces to write JavaScript inside of JSX?

Answer

Yes! If we want any expression to be treated as JavaScript inside of a JSX element we need to wrap it in curly braces. Even when we assign a JavaScript expression to a variable and want to use that variable inside JSX, the variable name needs to be wrapped in curly braces.

Example:
app.js:

import React from 'react';
import ReactDOM from 'react-dom';

let myVar = 'hello!';

const myJsxElement = <h1>myVar value is {myVar}</h1>; // `myVar` without curly braces will render as `myVar` in the browser, while `{myVar}` will render as `hello!` in the browser 

ReactDOM.render(
        myJsxElement,
        document.getElementById('app')
);
17 Likes