// ParentComponent.js: import React, { useState } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [parameterFromChild, setParameterFromChild] = useState(''); // Callback function to receive the parameter from the child const handleChildParameter = (parameter) => { setParameterFromChild(parameter); }; return ( <div> <h1>Parent Component</h1> {/* Render ChildComponent and pass the callback function as a prop */} <ChildComponent onParameterChange={handleChildParameter} /> {/* Display the parameter received from the child */} {parameterFromChild && ( <p>Parameter received from child: {parameterFromChild}</p> )} </div> ); }; export default ParentComponent; //ChildComponent.js: import React, { useState } from 'react'; const ChildComponent = ({ onParameterChange }) => { const [childParameter, setChildParameter] = useState(''); const handleButtonClick = () => { // Update the childParameter state setChildParameter('Hello from ChildComponent!'); // Invoke the callback function in the parent with the parameter onParameterChange('Hello from ChildComponent!'); }; return ( <div> <h2>Child Component</h2> <button onClick={handleButtonClick} className="bg-blue-500 text-white px-4 py-2"> Click me </button> </div> ); }; export default ChildComponent;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter