Reading an Input
React to every keystroke as someone types.
1import { useState } from 'react';
2
3function App() {
4 const [name, setName] = useState('friend');
5 return (
6 <div>
7 <input onChange={e => setName(e.target.value)} />
8 <p>Hello, {name}!</p>
9 </div>
10 );
11}
12export default App;
$ npm run dev
VITE v5.4 ready in 312 ms
Local: http://localhost:5173/
(your app is live: look at the browser window above!)
Every line, explained
import { useState } from 'react';- useState comes from the React library itself. This locked import line brings it in; you'll use it a few lines down.
function App() {- The App component: every lesson's page starts from this function.
const [name, setName] = useState('friend');- State again, but holding text this time, and starting as 'friend' so the page greets everyone before they type.
return (- When JSX spans several lines, it goes inside round brackets after return. The brackets keep the JSX attached to the return: without them, JavaScript would think the return finished at the end of that line and hand back nothing.
<div>- A component must return ONE outer tag. Putting two siblings side by side at the top level is an error, so a wrapping <div> holds them together.
<input onChange={e => setName(e.target.value)} />- <input> is a text box (self-closing, like <Greeting ... />). onChange fires on every keystroke, and e.target.value is whatever the box currently contains, so the state follows the typing letter by letter.
<p>Hello, {name}!</p>- The paragraph reads the state. Type in the box and this text changes with every key press. TRY IT in the browser window!
</div>- Closing tag for the wrapping div.
);- The ); closes the return's round bracket.
}- This } closes the component function.
export default App;- export default App hands your component to the rest of the app. A locked line in every lesson: the app's starter file (main.jsx) imports App and mounts it on the page.