Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from one component to another ReactJS

Tags:

reactjs

I have two components. The first has state initialized:

import React from 'react';

class One extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: 'hi'
        }
    }

    render() {
        return (

            <div prop={this.state.data}>{this.state.data}</div>  
        );
    }
}

export default One;
import React from 'react';

class Two extends React.Component {

    render() {
        return (
            <div>{this.prop}</div>     
        );
    }
}

export default Two;

The first component prints out the state of data. How would I pass that value into my second component as a read only value and render it?

like image 652
ShaneOG97 Avatar asked Jan 26 '23 01:01

ShaneOG97


2 Answers

To pass the value in the second component, you have to first import it in your first component and pass the value as prop.

For example, your code might look like this:

import React from 'react';
import Two from './Two' // I am assuming One.js and Two.js are in same folder.

class One extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: 'hi'
        }
    }

    render() {
        return (

            <div>
               <div>{this.state.data}</div>
               <Two value={this.state.data} />
            </div>
        );
    }
}

export default One;

And then in the Two.js you can access the value as below:


import React from 'react';

class Two extends React.Component {

    render() {
        return (
            <div>{this.props.value}</div>     
        );
    }
}

export default Two;

Now, let's say, you are using your component One in App or anywhere. Whenever you will use <One/> you will get following in the browser:

hi
hi
like image 71
Saqib Avatar answered Feb 20 '23 19:02

Saqib


You must call this 'Two' component into 'One' like this

One Component:

render() {
  return (
     <Two myProp={this.state.data} />
  )
}

You can call this whatever u wish (myProp)

And read this in 'Two' component:

render() {
  return (
     <div>Received data from parent Component: {this.props.myProp}</div>
  )
}

Before you call 'Two' component into 'One' you must import that file

import Two from './path/to/component';
like image 22
Freestyle09 Avatar answered Feb 20 '23 18:02

Freestyle09