Skip to main content

4.3 - Using JavaScript Within React


Why use JSX?

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.

HTML vs Javascript

In React, rendering logic and markup live together in the same place—components:

Components: HTML vs Javascript


JSX Rules

1. Return a single root element

  • To return multiple elements from a component, wrap them with a single parent tag. For example, you can use a <div>, or <> and </>:
//parent tag wrapper
<div>
<h1>Elaine's Bucket List</h1>
<Profile/>
<ul>
<li>Sleepover in Soda</li>
<li>Go to Croads</li>
<li>Touch grass</li>
</ul>
</div>

2. Close all the tags

  • JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />, and wrapping tags like <li>oranges must be written as <li>oranges</li>.

3. camelCase

  • In React, many HTML and SVG attributes are written in camelCase. For example, instead of stroke-width you use strokeWidth. Since class is a reserved word, in React you write className instead.

Displaying Variables

JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example:

const today = new Date();
const name = "Elaine";

function formatDate(date) {
return new Intl.DateTimeFormat(
'en-US',
{ weekday: 'long' }
).format(date);
}

export default function TodoList() {
return (
<h1>{name}'s To Do List for {formatDate(today)}</h1>
);
}

You can also use this during conditional rendering:

    <div>
{isLoggedIn && <AdminPanel />}
</div>

Where to use curly braces

You can only use curly braces in two ways inside JSX:

  1. As text directly inside a JSX tag: <h1>{name}'s To Do List</h1> works, but <{tag}>Elaine's To Do List</{tag}> will not.

  2. As attributes immediately following the = sign: src={avatar} will read the avatar variable, but src="{avatar}" will pass the string "{avatar}".

  3. Double curly braces: You can pass objects in JSX, in addition to strings, numbers, and other JavaScript expressions. Since objects are also denoted with curly braces, like { name: "Elaine", age: 20 }, you must wrap the object in another pair of curly braces: person={{ name: "Elaine", age: 20 }}.