Sub topic 3
How index.html and main.jsx Start the App
Assume basic HTML, JavaScript modules, React components, and terminal use. A Vite React app starts with an HTML document and a JavaScript entry module.
From `index.html` to React
index.html contains the page shell. Its <div id="root"></div> is the mounting point, an empty element where React places the application.
src/main.jsx imports React's createRoot function and the top-level App component. It connects App to the root element.
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)The browser loads the module through Vite's development server. Vite resolves imports, transforms JSX, and sends the result to the browser.
Run and edit the app
From the project directory, run:
npm run devVite prints a local URL, usually http://localhost:5173. Its hot module replacement, or HMR, updates changed modules in the browser without a full page reload. This keeps useful application state in many edits and shortens the feedback loop.
Add a component by creating src/Counter.jsx:
import { useState } from 'react'
export default function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}Then render it from App.jsx:
import Counter from './Counter.jsx'
export default function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
</main>
)
}Build, configure, and choose
npm run build creates an optimized dist bundle. Run npm run preview to serve that bundle locally and check the production output.
A typical vite.config.js enables React support:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})Vite exposes client variables only when their names begin with VITE_:
const apiUrl = import.meta.env.VITE_API_URLDo not put passwords or private keys in these variables. Client code is visible to users.
Exercise
What element does createRoot receive, and what does npm run build produce?
Show answer
It receives the element with the root ID. The build command produces an optimized bundle in dist.