Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 8, 2021 05:28 pm GMT

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 { 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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To