0.0.0 • Published 4 years ago

react-custom-events-hooks v0.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

react-custom-events-hooks

NPM version NPM downloads NPM license Codecov Travis Bundle size

About

Create custom events. Fast, simple, fun!

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