Logo


Sending props from child to parent in React js


In this tutorial,we are going to pass props from parent component to child component.In order to done this,we just need to pass a function as a prop from the parent component to the child component, and the child component calls that function.
In this example, we will change the Parent state by passing a function to the Child component and invoking that function inside the Child component.


contianer.js file is displayed below

1import React from "react";
2  class Parent extends React.Component {
3    constructor(props) {
4      super(props);
5      this.state = { childMsg: null };
6      this.outputEvent = this.outputEvent.bind(this);
7    }
8    outputEvent(childMsg) {
9      // the event context comes from the Child
10      this.setState({ childMsg: childMsg });
11    }
12    render() {
13      return (
14        <div>
15          Message from child or Props from child: {this.state.childMsg} <br />
16          <Child clickHandler={this.outputEvent} />
17        </div>
18      );
19    }
20  }
21  class Child extends React.Component {
22    render() {
23      return (
24        <button onClick={() => this.props.clickHandler("Hello World")}>
25          Add One More
26        </button>
27      );
28    }
29  }
30  export default Parent;

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share