React pass parameter from child --> parent

PHOTO EMBED

Sun Dec 17 2023 12:05:06 GMT+0000 (Coordinated Universal Time)

Saved by @eziokittu #react.js #javascript #css

// 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;
content_copyCOPY

https://chat.openai.com/c/9c689a90-e565-43b2-b16e-e4e64203e782