cool-hooks / react-custom-events-hooks

πŸ™Œ Create custom events. Fast, simple, fun!

Home Page:https://codesandbox.io/s/react-custom-events-hooks-i9eu2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react-custom-events-hooks

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

About

πŸ™Œ Create custom events. Fast, simple, fun!

https://codesandbox.io/s/react-custom-events-hooks-i9eu2

License:MIT License


Languages

Language:TypeScript 76.8%Language:JavaScript 23.2%