Passing data from child component to parent component in React JS

JavaScriptLeave a Comment on Passing data from child component to parent component in React JS

Passing data from child component to parent component in React JS

To pass data from a child component to a parent component in React, you can use callback functions that are passed down as props to the child component. The child component can then call these functions to pass data back up to the parent component.

// ParentComponent.js
import React from 'react';

const ParentComponent = () => {
  const [value, setValue] = React.useState('');

  const handleValueChange = (newValue) => {
    setValue(newValue);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent onValueChange={handleValueChange} />
      <p>{value}</p>
    </div>
  );
};

export default ParentComponent;

// ChildComponent.js
import React from 'react';

const ChildComponent = ({ onValueChange }) => {
  const [inputValue, setInputValue] = React.useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    onValueChange(inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={inputValue} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ChildComponent;

In this example, the ParentComponent uses the useState hook to store the value and provides a callback function handleValueChange to update the value. The handleValueChange function is passed as a prop onValueChange to the ChildComponent.

In the ChildComponent, the onValueChange prop is used to update the value in the ParentComponent when the form is submitted. The ChildComponent also uses a state hook to store the value of the input.

By using a callback function, you can pass data from a child component to a parent component and keep your components modular, making it easier to manage and maintain your application.

Another way to pass data from a child component to a parent component is using a state management library like Redux.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top