DEV Community

Cover image for How to pass props object from child component to parent
Harry
Harry

Posted on

How to pass props object from child component to parent

Before starting the topics let me tell me this is a hack I just found this today when I am doing my project.I facing a problem when I am trying to change data from child to parent .I remember I only know pass props from parent to child but I need to pass props from child to parents..Let's get started !

dancing

Requirements need to understand

  • What is props

Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.

Source

  • What is state

State is similar to props, but it is private and fully controlled by the component.You can make dynamic data using state.
source

Okay Now! Let't go into code .....

import { useState } from "react";
import Child from "./child";
const App = () => {
  const [Name, setName] = useState("Parent");

  return (
    <>
      <h1>{Name}</h1>
      <Child Changedata={(Name) => setName(Name)} />
    </>
  );
};

export default App;


Enter fullscreen mode Exit fullscreen mode

** In this parent component we have set initiate state value to "parent" and pass a function to the child component using props.


const Child = (props) => {
  return (

   <button 
   onClick={() => props.Changedata("Child")}>
   Change</button>

  )
};

export default Child;



Enter fullscreen mode Exit fullscreen mode

In child component we called that function using props.Changedata("child") and set a value inside the function parameter that value gonna effect to the state of parent's state and its turn into this value.
.

Demo link

Thus all for today If you found useful please share it to someone and I am waiting to see your feedback.Follow me on twitter

PS: I am just starting writing articles if any mistake feedback are welcome.

Top comments (0)