Hey, I’m working on a calculator, I’m trying to get the display to re render when a button is pressed but nothing is happening although the state is changing, the most common search result suggests componentWillMount()
but I thought that React would do this automatically.
I have three components: App (parent), Button and Display. App has a handleClick method: whatever button is clicked. Buttons have props which specify a number, and the handleClick method. When the handleClick method is clicked it takes the button’s prop as an argument then updates the state of the parent with that argument. This works but then the Display props do not update accordingly.
From my App (parent component with handleClick method)
this.State = {
calcValue: 0
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(val) {
console.log(val);
this.setState({ calcValue: val })
}
Button component where the actual click happens:
class Button extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<button onClick={() => this.props.handleClick(this.props.operator)}>
<div class={this.props.btn}>{this.props.operator}</div>
</button>
)
}
}
And lastly the display that should update from 0 (prop from parent’s initial state" to whatever number gets pressed):
class Display extends React.Component {
constructor(props){
super(props);
}
render() {
return(
<h1>{this.props.currentValue}</h1>
);
}
}
Can anyone walk me through where I am going wrong? For more context you can see the full pen here.