Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React | pass data from parent to child component

In React, I'm having Files like

--parent.js
--child.js
--App.js

parent.js contains Textbox and button

child.js contains P tag

App.js contains Both Parent and Child Component

Problem

Pass the Textbox value from Parent on button click to child and display the value in child paragraph tag.

Full Code stackblitz

like image 964
Selvin Avatar asked Dec 10 '22 07:12

Selvin


1 Answers

Updated your sample to pass data to child component.

https://stackblitz.com/edit/react-trmj9i?file=child.js

Adding code below for quick reference

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Parent from './parent';
import Child from './child';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      parentTextBoxValue: ''
    };
  }
  handleParentData = (e) => {
this.setState({parentTextBoxValue: e})
  }

  render() {
    return (
      <div>
        <Parent handleData={this.handleParentData} />
        <Child parentTextBoxValue={this.state.parentTextBoxValue}/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

parent.js

import React, { Component } from 'react';
import Button from 'react-uikit-button';

class Parent extends Component {

constructor(props){
    super(props);
    this.state={TextBoxValue: ""}
}   

  SubmitValue = (e) => {
     this.props.handleData(this.state.TextBoxValue)
  }

   onChange=(e)=>{
this.setState({TextBoxValue: e.target.value})
   } 
  render() {
    return (
      <div className="">
        <input type="text" name="TextBox"  onChange={this.onChange}
         />
        <Button onClick={this.SubmitValue}>Submit Value</Button>
      </div>
    );
  }
}

export default Parent;

child.js

import React, { Component } from 'react';

class Child extends Component {

    constructor(props){
        super(props);
    }


  render() {
    return (
      <div className="App">
       <p>{this.props.parentTextBoxValue}</p>
      </div>
    );
  }
}

export default Child;

Just to give what I did, Passed a function from App.js to parent which can be helped to lift the state up. handled onchange in parent component for text box and on submit updated app state. Finally passed this state to child component.

like image 190
G_S Avatar answered Dec 25 '22 22:12

G_S