Change Parent Component State From Child Component
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
Solution 1:
Do it in the same way as you are doing for Login, pass a function as a prop and call it on logout, see updates below.
constLoginScreen = () => (<div>Login Screen</div>);
classHomeextendsReact.Component {
constructor(props){
super(props);
this.state = {login : true};
this.logout = this.logout.bind(this);
}
login(){
// this method updates the login.state : true
}
logout() {
// this method updates the login.state : falsethis.setState({ login: false });
}
render() {
return (
<div>
{this.state.login ? (<ChatBoxuserNick="fad"onLogout={this.logout} />) : (<LoginScreenonSubmit={this.login} />) }
</div>
);
}
}
classChatBoxextendsReact.Component{
constructor(props) {
super(props)
// This makes sure `this` keeps pointing on this instance when logout is called from the outside.this.logout = this.logout.bind(this);
}
logout(){
// Call the onLogout property.this.props.onLogout();
}
render() {
return (
<divclassName="chat-box"><buttononClick={this.logout} > Logout </button><h3>Hi, {this.props.userNick} </h3></div>
);
}
}
ReactDOM.render(<Home />, document.querySelector('#main'));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="main"></div>
Solution 2:
You can pass an event from the Parent
component to the Child
component that handles the change of the state, like so:
classAppextendsReact.Component {
constructor() {
super();
this.state = { isLoggedIn: false };
}
_handleLogin() {
this.setState({ isLoggedIn: true });
}
_handleLogout() {
this.setState({ isLoggedIn: false });
}
render() {
const { isLoggedIn } = this.state;
return (
<div>
{
isLoggedIn ?
<ChatBoxlogoutEvent={this._handleLogout.bind(this)} />
:
<LoginloginEvent={this._handleLogin.bind(this)} />
}
</div>
);
}
}
constLogin = ({ loginEvent }) => (
<buttontype="button"onClick={loginEvent}>Login</button>
);
constChatBox = ({ logoutEvent }) => (
<div><h1>This is the Chat Box!</h1><buttontype="button"onClick={logoutEvent}>Logout</button></div>
);
ReactDOM.render(
<App />,
document.getElementById('container')
);
Here's the fiddle
Post a Comment for "Change Parent Component State From Child Component"