Create custom events. Fast, simple, fun!
Playground β play with the library in CodeSandbox
- react-custom-events-hooks by Harsh Rohila
- @use-it/event-listener by Donavon West
- react-event-hooks by Silvester Wilson Wennekers
First, install the library in your project by npm:
$ npm install react-custom-events-hooks
Or Yarn:
$ yarn add react-custom-events-hooks
β’ Import hooks in React application file:
import {
useCustomEvent,
useEmitter,
useListener,
} from 'react-custom-events-hooks';
import React, { useState } from 'react';
import {
useCustomEvent,
useEmitter,
useListener,
} from 'react-custom-events-hooks';
/* ------ Emit + Listen Example ------ */
const EmitListenExample = () => {
const [message, setMessage] = useState('');
const callMyEvent = useCustomEvent({
eventName: 'myAwesomeCustomEvent',
onSignal: (e) => setMessage(e.detail.message),
});
return (
<>
<p>{message}</p>
<button onClick={() => callMyEvent({ message: 'Hello World!' })}>
Say Hello!
</button>
</>
);
};
/* ------ Only Emit Example 1 ------ */
const EmitExample = () => {
const callMyEvent = useCustomEvent({
eventName: 'myAwesomeCustomEvent',
});
return (
<>
<button onClick={() => callMyEvent({ message: 'Hello World!' })}>
Say Hello!
</button>
</>
);
};
/* ------ Only Emit Example 2 ------ */
const EmitExample = () => {
const callMyEvent = useEmitter('myAwesomeCustomEvent');
return (
<>
<button onClick={() => callMyEvent({ message: 'Hello World!' })}>
Say Hello!
</button>
</>
);
};
/* ------ Only Listen Example 1 ------ */
const ListenExample = () => {
const [message, setMessage] = useState('');
useCustomEvent({
eventName: 'myAwesomeCustomEvent',
onSignal: (e) => setMessage(e.detail.message),
});
return (
<>
<p>{message}</p>
</>
);
};
/* ------ Only Listen Example 2 ------ */
const ListenExample = () => {
const [message, setMessage] = useState('');
useListener('myAwesomeCustomEvent', (e) => setMessage(e.detail.message));
return (
<>
<p>{message}</p>
</>
);
};
This project is licensed under the MIT License Β© 2020-present Jakub Biesiada