Reputation: 573
I'm trying to create a macro calculator using React.
I have a click handler that will setState
, but when the component refreshes, everything isn't saved in the state (I checked by going to the React Dev tools and viewing the component).
I'm pretty sure this is because when the component re-renders, the state is reinitialized as a blank object, as coded in my constructor function (if I'm wrong about this, please help me understand why state keeps showing up as blank).
I know it does work for a brief second before the component refreshes; I can see the state change to the proper values using the React Dev tools, and then it refreshes the component, and everything is blank again.
How can I fix this?
I thought about breaking this into even smaller components, but am not quite sure it's necessary.
import React from 'react';
class Macro extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleClick = this.handleClick.bind(this);
this.lbsToKg = this.lbsToKg.bind(this);
this.age = document.querySelector("#age");
}
ftToInch(ft) {
return ft * 12;
}
inchesToCm (inches) {
return inches * 2.54;
}
lbsToKg(lbs) {
return (Math.round(lbs * 0.45359237));
}
// mifflinStJeor(sex) {
// if ('male') {
// 10 * lbsToKg(this.state.weight) + 6.25 * height(cm) - 5 * this.state.age + 5
// } else {
// 10 * lbsToKg(this.state.weight) + 6.25 * height(cm) - 5 * this.state.age + 161
// }
// }
handleClick(e) {
this.setState({
weight: this.lbsToKg(document.querySelector("#weight").value),
age: document.querySelector("#age").value,
height: this.ftToInch(document.querySelector("#ft").value) + document.querySelector("#inches"),
})
}
render() {
return(
<div className='calculator-wrapper'>
<form>
<div className="sex">
<input type="radio" id="sex-male" />
<label htmlFor='sex-male'>Male</label>
<input type="radio" id="sex-female"/>
<label htmlFor='sex-female'>Female</label>
</div>
<div className="age">
<label htmlFor='age'>Age</label>
<input type="number" id='age' name="age" />
</div>
<div className="weight">
<label htmlFor='weight'>Weight</label>
<input type="number" id='weight' name="weight" />
</div>
<div className="height">
<label htmlFor='height'>Height</label>
<input type="number" id='ft' name="feet" placeholder="ft" />
<input type="number" id='inches' placeholder="inch" name="inches" />
</div>
<div className="output">
<input type="text" className="bmr-output" value={this.state.weight}/>
</div>
<div className="button">
<button className="bmr" onClick={this.handleClick}>Get BMR</button>
</div>
</form>
</div>
)
}
}
export default Macro;
Upvotes: 0
Views: 54
Reputation: 646
Since your button has no type associated with it, it is taking as type=submit
.
Which makes your form submit and refreshes the pages(actually submits the form).
To make it work at type=button
to button tag.
Upvotes: 4