In this blog post, I will walk you through a practical scenario where a parent component (ListBox) interacts with a child component (AlertComponent) using props and callbacks.
This is useful in React when you want a child component to communicate back to the parent to maintain state or trigger actions.
Let's understand with the help of this example:
Here’s the interaction breakdown:
import React, { useState } from 'react'; import AlertComponent from './AlertComponent'; const ListBox = () => { const [showComponent, setShowComponent] = useState(false); const alertAction = async () => { setShowComponent(!showComponent); }; return ( ); }; export default ListBox;{/* Passing props to the child component */}Item 1
{/* Other list items */}{ alert('Item Deleted'); setShowComponent(false); }} onCancel={() => setShowComponent(false)} showComponent={alertAction} />
export const AlertComponent: = ({ title, description, onAccept, onCancel, showComponent }) => { return (... rest of the code ) }
showComponent is working as a callback as it's maintaining the state which is responsible to show/hide the AlertComponent
Whenever Reject is pressed, this callback will toggle the current state of showComponent.
{ alert('Item Deleted'); setShowComponent(false); }} onCancel={() => setShowComponent(false)} showComponent={alertAction} />
Using props and callbacks in this way allows a clear flow of data between the parent and child components in React.
The parent can control state and pass it down to the child, while the child can communicate back via callbacks to inform the parent of any changes or actions the user has performed.
This is particularly useful for scenarios like showing alerts, modals, or pop-ups in response to user interaction.
Keep building!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3