Sub topic 12
How index.html and main.jsx start the app
This chapter assumes you have scaffolded a Vite React project and can run npm run dev. It also assumes you know ES modules (import and export) and what a component is. It follows the order the browser uses: HTML first, then the script, then React.
The page the browser loads
A Vite project keeps index.html at the project root, not in public/ or src/. Vite treats it as the entry of the app. The file is mostly empty:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My app</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>Two lines matter. The <div id="root"> is an empty container. React will fill it. The <script type="module"> loads src/main.jsx as an ES module. Vite reads this tag, so the path you write here is the real entry point of your code.
The entry file
src/main.jsx connects the page to your components:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)Each part has one job:
document.getElementById('root')finds the container inindex.html.createRoot(...)tells React that it owns everything inside that container..render(...)draws the given element tree inside the root.<App />is the top component. Every other component is nested under it.<StrictMode>adds extra checks in development only. For example, it runs some functions twice to expose side effects. It does not change what users see in the production build.
The package react-dom/client is separate from react. react defines components and hooks. react-dom knows how to put them in a browser page.
The startup sequence
Before the script runs, the page shows nothing from React. After render runs, React inserts DOM elements into #root. From then on, state changes update only the parts of the DOM that need to change.
Common errors
- A blank page and
Cannot read properties of nullin the console.getElementById('root')returnednull. The id inindex.htmland the id inmain.jsxdo not match, or the script runs before the element exists. - A 404 for
/src/main.jsx. Thesrcpath in the script tag is wrong. Paths starting with/are relative to the project root. Failed to resolve import './App.jsx'. The file name or extension is misspelled. Vite does not guess.jsxextensions as freely as some older tools, so write the extension.- A component is logged twice. This is
StrictModein development. It is expected.
Exercise
A teammate renames <div id="root"> to <div id="app"> in index.html and the page goes blank. What error do you expect, and what is the fix?
Show answer
document.getElementById('root') now returns null, so createRoot throws an error because it received no container. Fix it by changing main.jsx to document.getElementById('app'), or by restoring the id in index.html. The two ids must match.