Skip to content

cool-hooks/react-custom-events-hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

28 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NPM version NPM downloads NPM license Codecov Travis Bundle size

About

Create custom events. Fast, simple, fun!

Demo

Playground – play with the library in CodeSandbox

Alternatives

How to Install

First, install the library in your project by npm:

$ npm install react-custom-events-hooks

Or Yarn:

$ yarn add react-custom-events-hooks

Getting Started

β€’ Import hooks in React application file:

import {
  useCustomEvent,
  useEmitter,
  useListener,
} from 'react-custom-events-hooks';

Example

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>
    </>
  );
};

License

This project is licensed under the MIT License Β© 2020-present Jakub Biesiada