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.
const LoginScreen = () => (<div>Login Screen</div>);
class Home extends React.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 : false
this.setState({ login: false });
}
render() {
return (
<div>
{this.state.login ? (<ChatBox userNick="fad" onLogout={this.logout} />) : (<LoginScreen onSubmit={this.login} />) }
</div>
);
}
}
class ChatBox extends React.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 (
<div className="chat-box">
<button onClick={this.logout} > Logout </button>
<h3>Hi, {this.props.userNick} </h3>
</div>
);
}
}
ReactDOM.render(<Home />, document.querySelector('#main'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="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:
class App extends React.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 ?
<ChatBox logoutEvent={this._handleLogout.bind(this)} />
:
<Login loginEvent={this._handleLogin.bind(this)} />
}
</div>
);
}
}
const Login = ({ loginEvent }) => (
<button type="button" onClick={loginEvent}>Login</button>
);
const ChatBox = ({ logoutEvent }) => (
<div>
<h1>This is the Chat Box!</h1>
<button type="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"