An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
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 !
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.
- 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 { Component } from "react";import Child from "./child";class Parent extends Component { constructor(props) { super(props); this.state = { name: "Parend" }; } render() { return <Child name={this.state.name} />; }}
** In this parent component we have set the this.state.name = "parent" and pass its to child component using *** name *** attribute the value inside it call props.
import { useState } from "react";const Child = ({name})=>{ const [Name,setName] = useState(name); return( <> <h1 onClick={()=>setName("Child")}>{Name}</h1> </> )} export default Child;
First We destructer the value of props from parent component .Then we set a state Name to default value that come from parent and a event onClick to h1 when we click the h1 the value of parents of state value will change into child .
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.
Original Link: https://dev.to/hareom284/how-to-pass-props-object-from-child-component-to-parent-2a8d
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To