I know that the question with this title has already been asked few times before but the problem is that I couldn't get an appropriate answer. So as I am new to reactJS
and trying to create login logout form.
What I want to do is to pass or change a state of parent component from a child component through an event handler(When a user clicks on logout button). Below are the two Components:
First One:
class Home extends React.Component {
constructor(props){
super(props);
this.state = {login : false};
}
login(){
// this method updates the login.state : true
}
render() {
return (
<div>
{this.state.login ? (<ChatBox userNick="fad" />) : (<LoginScreen onSubmit={this.login} />) }
</div>
);
}
}
And Second:
class ChatBox extends React.Component{
logout(){
// Expecting or trying to update parent.state.login : false
// via this method as well
}
render() {
return (
<div className="chat-box">
<button onClick={this.logout} > Logout </button>
<h3>Hi, {this.props.userNick} </h3>
</div>
);
}
}
I have simplified these component to come on point.
What's going here?
Home
Component is the main parent component. Initially the state.login
is false
and in this situation LoginScreen
Components shows up. Now, when user login through LoginScreen
Component state.login
updates to true
, it's time to show for ChatBox
Component.
Now you can see that ChatBox
Component contains a button which calls a method logout
to logout user. What I want is to update once again the state.login
to false
in Home
Component When user click on the Logout Button.
I don't know how to do it, It will be appreciate if you help me.
Thanks in advance.