Unlocking the Power of Custom Events in React

Events are a fundamental aspect of the web, allowing us to respond to user interactions and create dynamic experiences. In React, events play a crucial role in managing state changes and updating the UI. While React provides a robust set of built-in events, there are times when we need to create custom events to handle specific use cases. In this article, we’ll explore the world of custom events in React and learn how to harness their power.

What are Custom Events?

Custom events are bespoke events created to handle specific situations that aren’t covered by React’s built-in events. They allow us to decouple components and communicate between them in a more flexible way. By creating custom events, we can notify other components of changes or actions, enabling us to build more complex and interactive applications.

Creating Custom Events in React

To create custom events in React, we’ll use the Event constructor and the CustomEvent interface. We’ll also use the detail property to pass data between components. Here’s an example:
jsx
const myEvent = new CustomEvent('myEvent', {
detail: 'Hello, World!',
});

Dispatching Custom Events

Once we’ve created our custom event, we need to dispatch it to notify other components. We can do this using the dispatchEvent method:
jsx
dispatchEvent(myEvent);

Subscribing to Custom Events

To listen for custom events, we’ll use the addEventListener method:
jsx
addEventListener('myEvent', (event) => {
console.log(event.detail); // Output: "Hello, World!"
});

Real-World Example: Building a Country List App

Let’s build a simple country list app that demonstrates how to use custom events in React. We’ll create two components: CountryList and ListControl. The CountryList component will display a list of countries, while the ListControl component will provide buttons to show or hide the list.

Project Setup

We’ll create a new React project using Create React App and add two components: CountryList.js and ListControl.js.

Building the Country List Component

The CountryList component will fetch a list of countries from an API and display them:
“`jsx
import React, { useState, useEffect } from ‘react’;

const CountryList = () => {
const [countries, setCountries] = useState([]);

useEffect(() => {
fetch(‘https://restcountries.com/v3.1/all’)
.then((response) => response.json())
.then((data) => setCountries(data));
}, []);

return (

    {countries.map((country) => (

  • ))}

);
};

export default CountryList;
“`
Building the List Control Component

The ListControl component will provide buttons to show or hide the list:
“`jsx
import React from ‘react’;

const ListControl = () => {
const handleShowList = () => {
dispatchEvent(new CustomEvent(‘showList’));
};

const handleHideList = () => {
dispatchEvent(new CustomEvent(‘hideList’));
};

return (

);
};

export default ListControl;
“`
Subscribing to Custom Events in the App Component

We’ll subscribe to the custom events in the App component:
“`jsx
import React, { useState, useEffect } from ‘react’;
import CountryList from ‘./CountryList’;
import ListControl from ‘./ListControl’;

const App = () => {
const [showList, setShowList] = useState(false);

useEffect(() => {
addEventListener(‘showList’, () => setShowList(true));
addEventListener(‘hideList’, () => setShowList(false));
}, []);

return (


{showList && }

);
};

export default App;
“`
Testing Custom Events

We’ll write unit tests to ensure our custom events are working as expected. We’ll use Jest to write tests for our components.

Conclusion

In this article, we learned about custom events in React and how to use them to communicate between components. We built a simple country list app that demonstrates how to create, dispatch, and subscribe to custom events. By harnessing the power of custom events, we can build more complex and interactive applications in React.

Leave a Reply

Your email address will not be published. Required fields are marked *