Components and JSX

Write a component and describe what it shows with JSX.

Your React code is compiled and run by React itself, inside your browser tab. Nothing to install.

Your first component

React builds a page out of components. A component is a JavaScript function that returns what should be on screen.

What it returns is written in JSX, which looks like HTML inside JavaScript: <h1> is a heading and <p> is a paragraph.

export default marks the component to show. Load the example and press Run.

Example
export default function App() {
  return (
    <div>
      <h1>Asha's Bakery</h1>
      <p>Fresh bread every morning.</p>
    </div>
  );
}

Your turn: a heading and a paragraph

The editor starts with the lines every component needs.

Practice task

Inside the div, show a main heading that says City Library and a paragraph that says Open every day.

Your answer is run and checked in the lesson. Try it now.

One thing is returned

A component returns one element. To show several, wrap them in one parent, such as a <div>.

Every tag must be closed. Tags with nothing inside close themselves with a slash: <br /> and <img />.

Example
export default function App() {
  return (
    <div>
      <h2>Opening hours</h2>
      <p>Monday to Saturday</p>
      <p>7 am to 2 pm</p>
    </div>
  );
}

Showing a value

Inside JSX, curly brackets switch back to JavaScript. Whatever value is between them is shown.

This is how a page shows something worked out, rather than typed in.

Example
export default function App() {
  const name = "Asha";
  const baked = 40;
  const sold = 28;
  return (
    <div>
      <p>Hello, {name}</p>
      <p>Loaves left: {baked - sold}</p>
    </div>
  );
}

Your turn: show a calculation

Use curly brackets inside the paragraph.

Practice task

Above the return, create two constants: price holding 40 and quantity holding 3. Show a paragraph that reads Total: 120, working the number out from the constants.

Your answer is run and checked in the lesson. Try it now.