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<boolean>(false); const alertAction = async () => { setShowComponent(!showComponent); }; return ( <div> <div onLongPress={alertAction}> <p>Item 1</p> {/* Other list items */} </div> {/* Passing props to the child component */} <AlertComponent title="Deleting item?" description="Click Accept to delete." onAccept={() => { alert('Item Deleted'); setShowComponent(false); }} onCancel={() => setShowComponent(false)} showComponent={alertAction} /> </div> ); }; export default ListBox;
export const AlertComponent: = ({ title, description, onAccept, onCancel, showComponent }) => { return (<AlertDialog> ... rest of the code </AlertDialog>) }
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.
<AlertComponent title="Deleting item?" description="Click Accept to delete." onAccept={() => { 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!
The above is the detailed content of Props and Callbacks in a shell. For more information, please follow other related articles on the PHP Chinese website!