JavaScript expressions in JSX

We wouldn't need React if all we wanted to do was render static HTML. That's where JSX offers us the ability to embed dynamic javascript content inside HTML. This gives us the power to use JavaScript variables or logic to render different HTML depending on the state of our app.

You can embed a JavaScript expression inside JSX by inserting the expression between the curly braces.

Javascript expressions are defined as part of JavaScript, and includes anything that resolves to a value: strings, numbers, booleans, arrays and so on. Some expressions do not render anything, as we'll show in the next lesson.

Objects, if statements and for/while loops are not valid JSX expressions. To render Objects, you must decide whether to render the keys or values of the object, parsing the object yourself with JavaScript commands. We'll discuss conditional rendering shortly.

Try it out yourself. Render some JavaScript inside curly braces.

Menu
Lesson 7/22
const myTask = "Swab the deck!";

export default function App() {
  return (
    <>
      <h1> 🏴‍☠️ The Captain's Tasks </h1>
      <p> Manage the daily jobs at sea </p>
      <ul>
        {/* myTask is a JavaScript expression evaluated with curly braces */}
        <li> {myTask} </li>
        {/* Any JavaScript expression can be evaluated inside curly braces */}
        <li> Discover {3 + 2} treasure chests </li>
        {/* Objects are not valid, this will raise an error 
           <li> {{a: 1}} </li> */}
      </ul>
    </>
  );
}