how to pass data from child component to its parent in reactjs?

  • Last Update :
  • Techknowledgy :

In the parent component, create a callback function. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component. Pass the callback function to the child as a props from the parent component. Following are the steps to pass data from child component to parent component:

This is our Splunktool team suggestion, we tried and its working fine ✌
//[CHILD]: Received data from parentimport { React, useState } from "react";
const Child = (props) => {
  const [data, setData] = useState("");
  const func = () => {
    props.myFunc(data);
  };
  return (
    <>
      <input
        type="text"
        value={data}
        onChange={(e) => setData(e.target.value)}
      />
      <button onClick={func}>Click</button>
    </>
  );
};
export default Child;
​
​
//[PARENT]:create a callback function in parentimport "./styles.css";
import Child from "./child";
export default function App() {
  const receivedData = (data) => {
    console.log(data);
  };
  return (
    <div className="App">
      <Child myFunc={receivedData} />
    </div>
  );
}
​

Creating React Application:

Step 1: Create a React application using the following command:

npx create - react - app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Filepath- src/component/Child.js

import React from 'react'
class Child extends React.Component{
    
    onTrigger = (event) => {
        this.props.parentCallback(event.target.myname.value);
        event.preventDefault();
    }
  
    render(){
        return(
        <div>
            <form onSubmit = {this.onTrigger}>
                <input type = "text" 
                name = "myname" placeholder = "Enter Name"/>
                <br></br><br></br>
                <input type = "submit" value = "Submit"/>
                <br></br><br></br>
            </form>
        </div>
        )
    }
}
export default Child

Suggestion : 2

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent. In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent. You can even avoid the function at the parent updating the state directly React.createClass method has been deprecated in the new version of React, you can do it very simply in the following way make one functional component and another class component to maintain state:

Short Answer

Parent:

<div className="col-sm-9">
     <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
</div>

Child:

handleLangChange = () => {
   var lang = this.dropdown.value;
   this.props.onSelectLanguage(lang);
}

Considering React.createClass is deprecated from v16.0 onwards, It is better to go ahead and create a React Component by extending React.Component. Passing data from child to parent component with this syntax will look like

Parent

class ParentComponent extends React.Component {

    state = { language: '' }

    handleLanguage = (langValue) => {
        this.setState({language: langValue});
    }

    render() {
         return (
                <div className="col-sm-9">
                    <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
                </div>
        )
     }
}

Using createClass syntax which the OP used in his answer Parent

const ParentComponent = React.createClass({
    getInitialState() {
        return {
            language: '',
        };
    },

    handleLanguage: function(langValue) {
        this.setState({language: langValue});
    },

    render() {
         return (
                <div className="col-sm-9">
                    <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
                </div>
        );
});

Child

var json = require("json!../languages.json");
var jsonArray = json.languages;

export const SelectLanguage = React.createClass({
    getInitialState: function() {
        return {
            selectedCode: '',
            selectedLanguage: jsonArray[0],
        };
    },

    handleLangChange: function () {
        var lang = this.refs.dropdown.value;
        this.props.onSelectLanguage(lang);            
    },

    render() {

        return (
            <div>
                <DropdownList ref='dropdown'
                    data={jsonArray} 
                    valueField='lang' textField='lang'
                    caseSensitive={false} 
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />
            </div>            
        );
    }
});

Suggestion : 3

First, you need to create a function in the parent component called  childToParent and an empty state named data. Next, in the parent component, accept this data in the childToParent function as a parameter. Then set the data using the useState hook. Just call an alert method in the childToParent function and pass that function as a prop to the child component. Your function in the parent component will be called out when you click the button in the child component and you will see this alert:

1._
import React from 'react'

export default function Parent() {
  return (
    <div>
      
    </div>
  )
}
2._
import React from 'react'

export default function Child() {
    return (
        <div>
            
        </div>
    )
}
3._
import React from 'react'
import Child from './Child';

export default function Parent() {
  return (
    <div>
      <Child/>
    </div>
  )
}
5._
<Child parentToChild={data}/>
6._
import React from 'react'

export default function Child({parentToChild}) {
    return (
        <div>
            {parentToChild}
        </div>
    )
}

Suggestion : 4

Sometimes we need to pass data from a child component to parent component. For example we can have an input child component and a parent that shows the input when input is updated. Let’s make an example of it. As you can see, we have a text state and a changeState function. We pass changeState function to the Input component, that way the child component is able to pass data to the parent component. Basically, we pass an event handler function to our child component, that modifies the parent component’s state.

Create a react app with create-react-app and create an Input.js file:

src/Input.js

import React from 'react';
import styled from 'styled-components'

const Input = ({
    changeState
}) => {

    return (
        <StyledInput
            type="text"
            onChange={changeState}
        />
    )
}
const StyledInput = styled.input`
width:20rem;
height:2rem;
border-radius:0.5rem;
border:2px solid black;
margin:5% 0 0 20%;
outline:none;
`
export default Input

The child component takes a function prop, and this function actually updates the state of the parent component. Jump into App.js and modify it like this:

src/App.js

import React, { useState } from 'react';
import Input from './Input';
import styled from 'styled-components';

const App = () => {
  const [text, setText] = useState("");
  const changeState = (e) => {
    const value = e.target.value;
    setText(value);
  }
  return (
    <>
      <StyledText>{text}</StyledText>
      <Input
        changeState={changeState}
      />
    </>
  )
}
const StyledText = styled.div`
margin:0 0 0 20%;
`

export default App

Suggestion : 5

After Pass Handle into Child Component, We Have to Create One Button in Child Component, in This Button We Have to Create an onClick Event That Event Pass Handle That sends Data into Parent Component. After creating State We Have To Add the Child Component Into the Parent Component and Pass State Data In to Child Component After Get Data from Parent to Child Using Props, If We Want to Share Data From Child To Parents We Have To Create One Handle That Change Parent State Data, So Create One Handle In Parent Component, and Pass Handle Into Child Component.

1._
import React from 'react'
const ParentComponent = () => {
    return (
        <div>
            Hello Parent Component
        </div>
    )
}
export default ParentComponent
2._
import react from "react";
import ParentComponent from "./ParentComponent";

function App() {
    return <div><ParentComponent/></div>;
}
export default App;
3._
import React from 'react'
const ChildComponent = () => {
    return (
        <div>
            Hello Child Component
        </div>
    )
}
export default ChildComponent
5._
import React,{useState} from 'react'
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
    const [stateName,setStateName]=useState("Hello World");
    return (
        <div>
            <ChildComponent stateName={stateName}/>
        </div>
    )
}
export default ParentComponent
6._
import React from 'react'
const ChildComponent = (props) => {
    return (
        <div>
            {props.stateName}
        </div>
    )
}
export default ChildComponent