DebugFactor.com | Forum

How to pass data from Child Component to Parent Component in ReactJS?

How can I pass data from my child component to the parent component in react? Both of the components are react class components defined in separate JSX files.

In react, there are multiple ways to pass data from the child component to the parent component.

Option 1

Pass a function to the Child Component through props and invoke it from Child Component:

import React from "react";

class ParentController extends React.Component {

  updateDataHandler = (data) => {
     this.setState({data: data});
  }

  render = () => {
     return (
        <ChildComponent updateData={this.updateDataHandler} />
     )
  }
}

In Child Controller, invoke the method in Parent Controller as this.props.updateData()

import React from "react";

class ChildComponent extends React.Controller {
  render = () => { 
    return (
      <Button onClick={this.props.updateData('Data from Child Component')}>
    )
  }
}

This react design pattern is called as Render Props which is basically sharing code between components by having props whose value is a function.