ReactJS - Events
ReactJS - Event Handling
Section titled “ReactJS - Event Handling”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.
Simple Event Example
Section titled “Simple Event Example”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.
App.jsx
Section titled “App.jsx”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;main.js (or index.js)
Section titled “main.js (or index.js)”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!’.
Communicating Events from Child to Parent
Section titled “Communicating Events from Child to Parent”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.
App.jsx
Section titled “App.jsx”import React, { useState } from 'react';
// Child Componentconst Content = (props) => { return ( <div> <button onClick={props.onUpdateData}>CLICK IN CHILD</button> <h3>{props.currentData}</h3> </div> );}
// Parent Componentfunction 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;main.js (or index.js)
Section titled “main.js (or index.js)”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.