Reputation: 407
I have "RootComponent" which has a state isLoggedIn and loads Login and Home as:
..
..
switch (this.state.isLoggedIn) {
case 'true':
return (
<Home />
);
case 'false':
return (
<Login />
);
default:
return <Spinner size='large' color='red' />;
}
...
In Login I want to change isLoggedIn state when login button is pressed and rerender to Home screen. Without using Redux.
Upvotes: 1
Views: 1173
Reputation: 2052
You'll need to pass a function to the login component that once logged in will be called and update the state of the parent:
...
switch (this.state.isLoggedIn) {
case 'true':
return (
<Home />
);
case 'false':
return (
<Login updateLoginState={() => this.setState(state => ({ isLoggedIn: 'true'}))} />
);
default:
return <Spinner size='large' color='red' />;
}
...
and in your Login component you simply call this.props.updateLoginState()
at the point that the login process is finished
Although I'm not sure how you're reach the spinner state...
Upvotes: 2
Reputation: 4537
Your parent component should be passing the props to both the Login and Home component. What you need is a method in the parent component which updates the state of the parent component. The method will be passed down as a prop to Login component.
Your root component should look something like this
handleClick() { this.setState({isLoggedIn: true}); }
render() {
return (
{!this.state.isLoggedIn && <Login handleClick={this.handleClick}/>}
{this.state.isLoggedIn && <Home />
);}
Your Login component
render() { return (<Button
onPress={this.props.handleClick}
title="Press Me"
/>;}
Flow -
When user clicks on the button, the handleClick
function will be called which is passed down as props. So, the method in the parent component will be executed and this will update the state isLoggedIn
. Once the state is updated, the new values will be passed down to the Login and Home component, and they will treat it as updated props and hence will re-render
Upvotes: 1