JSX Is JavaScript

JSX looks like HTML, but browsers don't understand it. Before your code runs, a tool turns each piece of JSX into an ordinary function call. (In a project on your computer, the tool is Vite; here, the exercise page does it.) This line:

const heading = <h1>Summer Sounds</h1>;

becomes, in short, this:

const heading = jsx("h1", { children: "Summer Sounds" });

The function jsx() comes from React. It makes an object that describes the element: its tag and what's inside it, its children. React then makes the real elements on the page from these objects. You'll never write jsx() yourself, but knowing it's there explains the rules of JSX that this lesson is about.

The first one: a component returns one element. A function returns one value, and two elements side by side would be two calls side by side, jsx("h1", …) jsx("ul", …), which isn't JavaScript. That's why the red message under the preview says JSX expressions must have one parent element. Put them into one element, such as main, and they're one value.

Sometimes you don't want an extra element on the page. A component that returns several items of a list can't put them into a div element, because in a ul, there should be only li elements. For that, JSX has the fragment, an empty tag <>…</>. It holds the elements together in the code, but adds nothing to the page:

function SaturdayBands() {
    return (
        <>
            <li>Owl Choir, 16:00</li>
            <li>Tin Robots, 21:00</li>
        </>
    );
}

<SaturdayBands /> in a ul puts two li elements right into the list.

Instructions

Under the heading, add a list ul with <FridayBands /> in it. Then App returns two elements, so put the heading and the list into one main element.

FridayBands shows only Lunar Cats. Add a second li after it, Night Trains, 20:00, and put both into a fragment, so that they go right into the list.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/9

Next