1.0.6 • Published 1 year ago

@anissoft/react-events v1.0.6

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

React Events

Use this if you want to send custom events or messages from one React component to another, without lifting state or using refs.

Installation

Just run npm install command:

$ npm install @anissoft/react-events

Usage

Just wrap your application in :

import React from "react";
import ReactDOM from "react-dom";
import { CustomEventScope } from "@anissoft/react-events";

/* ... */

ReactDOM.render(
  <CustomEventScope>
    <App />
  </CustomEventScope>,
  root
);

You can add event listener with hooks useAddCustomEventListener or useCusomEventListener:

import { useAddCustomEventListener } from "@anissoft/react-events";

function Component() {
  const addCustomeEventListener = useAddCustomEventListener();

  React.useEffect(() => {
    const removeEventListener = addCustomeEventListener("EventName", function listener(payload) {
      console.log(paylaod);
    });
  }, [...depsArray]);

  //...
}

or it's equivalent:

import { useCustomEventListener } from "@anissoft/react-events";

function Component() {
  useCustomEventListener(
    "EventName",
    function listener(payload) {
      console.log(paylaod);
    },
    [...depsArray]
  );

  //...
}

To dispatch event - use hook useDispatchCustomEvent:

import { useDispatchCustomEvent } from "@anissoft/react-events";

function Component() {
  const dispatchCustomeEvent = useDispatchCustomEvent();

  React.useEffect(() => {
    dispatchCustomeEvent("EventName", { data: "Some string" });
  }, []);
  //...
}

If you are using nested CustomScopes, you can isolate any of them - just pass prop isolate=true:

  <CustomEventScope>
    {/* no events from child Scope will be fired in parent Scope  */}
     <CustomEventScope isolate>
     </CustomEventScope>
  </CustomEventScope>,

Additional API

  • addGlobalEventListener - add event listener outside of React application;
  • removeGlobalEventListener - remove global event listener outside of React application;
  • dispatchGlobalEvent - fire event on global level;
1.0.6

1 year ago

1.0.4

2 years ago

1.0.1

3 years ago

1.0.0

3 years ago