Jack M. Jack M. - 3 months ago 13
React JSX Question

React: Children onclick to change parent's state for re-rendering

I'm really new with react. I'm trying to get the parent to change page displayed depending on the states. I have a button in my sub-component that should send "true" or "false" to the parent component so it knows if to render it or not. I think it should be done with props like this:

this.state = {
btnNewScreen: this.props.btnNewScreen //true or false
};


But im not getting it to work. Could you give any tips? Here is the full parent - child

parent - maindisplay.js

import React from 'react';
import Mainpage_Addscreen from '../components/subcomponents/mainpage-addscreen';
import Mainpage_Showscreens from '../components/subcomponents/mainpage-showscreens';
//
class MainDisplay extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: false //should be this.props.btnNewScreen?
};
}

render() {
var renderThis;
if (!this.state.btnNewScreen) {
renderThis =
<div>
<Mainpage_Addscreen />
<Mainpage_Showscreens />
</div>
}
else {
//renderThis = <AddScreen />
renderThis =
<div>
<Mainpage_Addscreen />
<h3>Change to this when true (button click)</h3>
</div>
}
return (
<div>
{renderThis}
</div>
);
}
}


export default MainDisplay;


child - mainpage-addscreen.js

import React from 'react';

import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Button from 'react-bootstrap/lib/Button';

class Mainpage_Addscreen extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: true
};
this.newScreen = this.newScreen.bind(this);
}

newScreen(e) {
this.setState({ btnNewScreen: !this.state.btnNewScreen });
console.log(this.state.btnNewScreen);
}
render() {
var text = this.state.btnNewScreen ? 'Add new' : 'Screens';
return (
<div className="main_window col-sm-offset-1 col-sm-10">
<h3 id="addscreens">Screens: </h3>
<Button id="addScreen" className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" onClick={this.newScreen}><Glyphicon id="refresh_screens" glyph="plus" />&nbsp; {text}</Button>
</div>
);
}
}


export default Mainpage_Addscreen;

Answer

What you need to do is to pass a method from the parent to the child, That it can call when the button is clicked. This method that belongs to the parent will change the state.
In MainPage.js

changeButtonState(event) {
    this.setState({btnNewScreen: !this.state.btnNewScreen})
}

pass this method to your child component as
<Mainpage_Addscreen buttonClick={this.changeButtonState.bind(this)/>

and finally in the child component,
<Button .... onClick={this.props.buttonClick} />

Comments