Skip to content

ReactJS - Events

In this chapter, we’ll explore how to handle events in React. React events are named using camelCase, rather than lowercase (e.g., onClick instead of onclick). With JSX, you pass a function as the event handler, rather than a string.

This example demonstrates a simple event handler in a functional component. We use the useState hook to manage a piece of data. The onClick event on the button triggers the updateData function, which then updates the component’s state.

import React, { useState } from 'react';
function App() {
const [data, setData] = useState('Initial data...');
const handleUpdateData = () => {
setData('Data updated!');
};
return (
<div>
<button onClick={handleUpdateData}>CLICK ME</button>
<h4>{data}</h4>
</div>
);
}
export default App;
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);

When you click the ‘CLICK ME’ button, the text below it will change from ‘Initial data…’ to ‘Data updated!’.

A common pattern in React is for a parent component to manage state and pass down functions to child components that can trigger state updates in the parent. The child component receives this function as a prop and calls it when a specific event occurs.

import React, { useState } from 'react';
// Child Component
const Content = (props) => {
return (
<div>
<button onClick={props.onUpdateData}>CLICK IN CHILD</button>
<h3>{props.currentData}</h3>
</div>
);
}
// Parent Component
function App() {
const [data, setData] = useState('Initial data from parent...');
const handleUpdateDataFromChild = () => {
setData('Data updated from the child component!');
};
return (
<div>
<Content
currentData={data}
onUpdateData={handleUpdateDataFromChild}
/>
</div>
);
}
export default App;
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);

In this setup, clicking the ‘CLICK IN CHILD’ button (rendered by the Content component) will call handleUpdateDataFromChild in the App component. This updates the data state in App, and the new data (‘Data updated from the child component!’) is displayed within the Content component. This demonstrates unidirectional data flow and event handling between parent and child components.