Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access state of one component into another component in react

Tags:

reactjs

import React, { Component } from 'react';
class one extends React.Component 
{
    constructor()
    {
        super();
        this.state = {
            number:26
        }
    }
    render()
    {
        return(
            <div></div>
        );
    }
}
export default one;

import React, { Component } from 'react';
import one from './one'
class HomePage extends React.Component 
{
    render()
    {
        return(
            <div>{one.state.number}</div>
        );
    }
}
export default HomePage;

is it possible to access number state is there any way to access state of one component into another component? please suggest me if any solution is present.

like image 355
Kailash Choudhary Avatar asked Dec 19 '22 03:12

Kailash Choudhary


1 Answers

As Shubam has explained it, Though I would like to form it as a complete answer

First of all, I would like to let you know that Never Use lowercase letters to name your React Components.So name your component to One instead of one.

Now Comming back to your question:- No This is not Possible, If your app contains few components then it's better to pass the state object as the props, But if your app contains too many components then better to use predictable state containers like Redux or Flux rather than passing state as props.

So you may apply these changes and I hope You will get What You Desire:-

One Component:-

import React, { Component } from 'react';
import Homepage from './homepage';

class One extends React.Component 
{
    constructor()
    {
        super();
        this.state = {
            number:26
        }
    }
    render()
    {
        return(
            <Homepage data={this.state}/>
        );
    }
}

export default One;

Homepage Component:-

import React, { Component } from 'react';


class Homepage extends React.Component 
{

    render()
    {
        console.log("this is homepage",this.props);
        return(
            <div>{this.props.data.number}</div>
        );
    }
}

export default Homepage;

Please Raise Your doubts if any, Or if you find any error in it.

like image 113
Vinit Raj Avatar answered Dec 31 '22 03:12

Vinit Raj