Mark As Completed Discussion

Handling Events in Components

In React, you can handle user interactions and events by adding event handlers to your components. Event handlers are functions that are executed when a certain event occurs, such as a button click or a form submission.

Let's create a simple button component that triggers an event when clicked:

SNIPPET
1function Button(props) {
2  const handleClick = () => {
3    // Handle the click event here
4    console.log('Button clicked!');
5  };
6
7  return (
8    <button onClick={handleClick}>{props.label}</button>
9  );
10}
11
12function App() {
13  return (
14    <div>
15      <h1>Handling Events in Components</h1>
16      <p>In React, you can handle user interactions and events by adding event handlers to your components. Let's create a simple button component that triggers an event when clicked.</p>
17      <Button label="Click me!" />
18    </div>
19  );
20}
21
22ReactDOM.render(
23  <React.StrictMode>
24    <App />
25  </React.StrictMode>,
26  document.getElementById('root')
27);

In this example, we have a Button component that takes a label prop. Inside the component, we define a function handleClick that gets executed when the button is clicked. The handleClick function simply logs a message to the console.

The button element has an onClick attribute that is assigned the handleClick function. This binds the function as the event handler for the button's click event.

When the button is clicked, the handleClick function is executed, and the message 'Button clicked!' is logged to the console.

You can modify the handleClick function to perform any desired action when the button is clicked, such as updating state, making API calls, or navigating to another page.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment