1.0.2 • Published 6 months ago
send-data-to-parent v1.0.2
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
Prop | Type | Default | Description |
---|---|---|---|
sendData | Function | undefined | Callback function to handle the captured data. |
filterCondition | Function | undefined | Optional filter for custom conditions. |
preventPropagation | Boolean | true | Whether to stop event propagation. |
eventsToTrack | Array | ["click"] | List of events to listen for (e.g., "click" , "change" ). |
id | String | undefined | Target ID to match elements. |
children | ReactNode | undefined | Child components to wrap and monitor for events. |
Example Use Cases
- Tracking Button Clicks: Monitor specific buttons and log their IDs or content when clicked.
- Form Input Changes: Capture and handle input changes dynamically.
- Event Filtering: Use
filterCondition
to capture only specific events based on custom logic.
License
This project is licensed under the MIT License.