1.0.2 • Published 6 months ago

send-data-to-parent v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

SendDataToParent

SendDataToParent is a React library designed to capture and handle events on child components and pass data back to the parent component through callbacks. It supports event filtering, propagation prevention, and dynamic event tracking.

Installation

npm install send-data-to-parent

Usage

Basic Example

In your index.js:

import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import { BrowserRouter } from 'react-router-dom';
import { SendDataToParent } from 'send-data-to-parent';

const sendDataOnClick = (data) => {
  console.log('Clicked element data:', data);
};

createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <SendDataToParent id="targetElement" sendData={sendDataOnClick} eventsToTrack={["click"]}>
      <App />
    </SendDataToParent>
  </BrowserRouter>
);

In your App.jsx:

import React from 'react';
import Home from './Home';

const App = () => {
  return (
    <div>
      <Home />
    </div>
  );
};

export default App;

Scenario: Wrapping Specific Components

If you wrap a specific component, such as Home, with SendDataToParent, you will receive event data for all matching elements within the Home component.

In App.jsx:

import React from 'react';
import Home from './Home';
import { SendDataToParent } from 'send-data-to-parent';

const sendDataOnClick = (data) => {
  console.log('Clicked element data:', data);
};

const App = () => {
  return (
    <SendDataToParent id="homeButton" sendData={sendDataOnClick} eventsToTrack={["click"]}>
      <Home />
    </SendDataToParent>
  );
};

export default App;

In Home.jsx:

import React from 'react';

const Home = () => {
  return (
    <div>
      <button id="homeButton">Click Me</button>
      <input id="homeInput" type="text" placeholder="Type here" />
    </div>
  );
};

export default Home;

When the button or input within the Home component is interacted with, the sendDataOnClick callback will capture the event data and log it.

API

Props

PropTypeDefaultDescription
sendDataFunctionundefinedCallback function to handle the captured data.
filterConditionFunctionundefinedOptional filter for custom conditions.
preventPropagationBooleantrueWhether to stop event propagation.
eventsToTrackArray["click"]List of events to listen for (e.g., "click", "change").
idStringundefinedTarget ID to match elements.
childrenReactNodeundefinedChild components to wrap and monitor for events.

Example Use Cases

  1. Tracking Button Clicks: Monitor specific buttons and log their IDs or content when clicked.
  2. Form Input Changes: Capture and handle input changes dynamically.
  3. Event Filtering: Use filterCondition to capture only specific events based on custom logic.

License

This project is licensed under the MIT License.

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago