Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 2.2Rendering your first component

A Vite React project begins with an HTML element whose id is root. The JavaScript entry file gives React control of that element and renders the top-level component.

The React root

JSX
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
const rootElement = document.getElementById(
  "root"
);
const root = createRoot(rootElement);

root.render(
  <App />
);

The App component

JSX
export default function App() {
  return (
    <main>
      <h1>My tasks</h1>
      <p>Three tasks remaining</p>
    </main>
  );
}

Component rules

Component names begin with a capital letter so React can distinguish them from HTML elements. A component returns one root element; use a fragment, written <>...</>, when an extra DOM element would be meaningless. Keep components pure: calculate their output without changing values outside the component.

How the two files connect

Execution begins in main.jsx. The first import takes createRoot from React's browser package. The second follows the default export from App.jsx and gives it the local name App.

  1. document.getElementById("root") finds <div id="root"></div> in index.html.
  2. createRoot(...) creates React's connection to that DOM element.
  3. <App /> asks React to render the imported component.
  4. React calls App, receives its JSX and creates the corresponding main, h1 and p elements.

The slash closes a component with no nested content. JSX lets React control when the function renders instead of you calling App() directly.

What you should see

The page shows a My tasks heading followed by Three tasks remaining. If it is blank, check the browser console. A misspelled root, missing export or incorrect filename usually produces a useful error.

Challenge: add a second component

Create a Footer function that returns a footer containing your name. Render it after main without adding a meaningless wrapper div.

Hint

Wrap main and Footer in a fragment: <>...</>.

One solution
function Footer() {
  return <footer>Built by Jamie</footer>;
}

export default function App() {
  return <>
    <main><h1>My tasks</h1><p>Three tasks remaining</p></main>
    <Footer />
  </>;
}
Feedback 👍
Comments are sent via email to me.