Tobi
Tobi

Reputation: 43

Set state from another component React js

I have the following structure in index.js :

<MyAppBar // + properties/>
 <Route path={path} component={Login}/>

MyAppBar.js

 class MyAppBar extends React.Component {

state = {
  auth: false,
  anchorElement: null
};

handleLogin(){
  this.setState({auth:true});
}

//another code
//end component

export default withStyles(styles)(MyAppBar)

I want to update MyAppBar state auth flag to be true from within the Login component action handler (i.e. handleLogin), but I do not know how.

I've tried with importing MyAppBar (all component) on the Login page, but it says that

MyAppBar.handleLogin(); 

is not a function... Thank you!

Thank you!

Upvotes: 0

Views: 6707

Answers (4)

Hasan Sh
Hasan Sh

Reputation: 1063

I don't think for this simple paradigm you'll need to go through all the hassle of setting redux up(I love Redux, but sometimes we don't have to use it)

Here's how you could implement it with the new context.

Edit React Hooks

It's farily simple and nice to use. Check it here Let me know if that isn't clear.

Upvotes: 1

Sujit.Warrier
Sujit.Warrier

Reputation: 2889

its better to use redux in such scenarios, as that makes communication between components very easy. Else if you want to go the hard way, then create a parent component, that will wrap both login and MyAppBar.

  class ParentComp extends Component{
      constructor(props){ 
         super(props);
         this.state={
             isLoggedIn:false
         };
        this.setLoginState=this.setLoginState.bind(this);
      }
      setLoginState(value){
          this.setState({isLoggedIn:value});
      }

       render(){
         return(<div>
                   <MyAppBar isLoggedIn={this.state.isLoggedIn} />
               <Route path={path} render={props=><Login {..props} setLoginState={this.setLoginState}/>}/>
                </div>);
       }
  }

in your LoginComponent call the setLoginState method

   this.props.setLoginState(true);

and in your myappbar component use the isLoggedIn prop to render conditionally

   renderLogin(){
     if(this.props.isLoggedIn){ 
          // return loggedin jsx
     }else{
         return the alternative
     }
   }

Upvotes: 0

FurkanO
FurkanO

Reputation: 7308

You should use REDUX.

Mostly because it lets you have a state that any component can read or can be synced with.

I rarely use react's state/setState.

In most cases redux state is good to change/watch.

Upvotes: 0

Sinane
Sinane

Reputation: 2010

Login should be a children component of MyAppBar. Then you could pass function handleLogin as a props to Login.

Upvotes: 0

Related Questions