Events and Forms
React handles events with attributes such as onClick and onChange (camelCase). Give them a function.
For a text box, keep its value in state and update it on every key press. This is called a controlled input.
Events are how users interact with your app: clicking a button, typing, submitting a form, choosing from a drop-down. In React, you attach a function to the element, and React calls it with an event object that describes what happened (for example e.target.value is the text in an input).
With a controlled input, React state is the "single source of truth" for the text box. Every key press updates the state, and the box shows the state. This makes it easy to validate as the user types, format values, enable or disable a submit button, or clear the form after saving. For forms, call e.preventDefault() on submit to stop the browser from reloading the page.
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
function Search() {
const [text, setText] = React.useState("");
return (
<div>
<input
value={text}
onChange={e => setText(e.target.value)}
placeholder="Search a product"
/>
<p>You are searching for: <b>{text}</b></p>
<button onClick={() => alert("Searching " + text)}>Search</button>
</div>
);
}
function App() {
return <Search />;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfonClick={save} or onClick={() => save(1)}. Writing onClick={save()} runs it immediately.- Event props like
onClickandonChangetake a function. - Controlled inputs keep their value in state.
- Use
e.preventDefault()on form submit.
