I am trying to build a React app where i can input my weight and height and it will count value of my BMI and show it on a diagram. I did not want to make everything in one component so i divided it into small components.
Here is the main App Component:
const App_function = () => {
const [arrayBMI, setArrayBMI]=useState([]);
const [dateArray, setDateArray]=useState([]);
const handlerMain = (heightData, weightData) => {
const valueOfBMI = weightData / (heightData/100*heightData/100);
console.log(valueOfBMI);
const repMainArray = arrayBMI;
repMainArray.push(valueOfBMI);
setArrayBMI(repMainArray);
const repDateArray = dateArray;
let currentDateData = new Date();
let day = currentDateData.getDate();
if(day < 10) {
day = '0' + day;
}
let month = currentDateData.getMonth() + 1;
if(month < 10) {
month = '0' + month;
}
let year = currentDateData.getFullYear();
let date = `${day}-${month}-${year}`;
repDateArray.push(date);
setDateArray(repDateArray);
}
return (
<div>
<Data handlerFunction={handlerMain}/>
<Diagram arrayMain={arrayBMI} arrayOfDate={dateArray}/>
<div>{arrayBMI[0]} a {arrayBMI[1]}</div>
<StoragE/>
</div>
);
}
And here is the Data Component:
function data_function(props) {
function formCloser(event) {
event.preventDefault();
let heightField = event.target.querySelector('#height').value;
let weightField = event.target.querySelector('#weight').value;
props.handlerFunction(heightField, weightField);
event.target.querySelector('#height').value='';
event.target.querySelector('#weight').value='';
}
return (
<div className="main-div">
<p className="paragraph-boy">BMI Calculator</p>
<form onSubmit={formCloser}>
<div className="inputs">
<div className="input_fields">
<label htmlFor="weight">Weight (in kg)</label>
<input type="text" id="weight" placeholder="50" autoComplete="off"></input>
</div>
<div className="input_fields">
<label htmlFor="height">Height (in cm)</label>
<input type="text" id="height" placeholder="175" autoComplete="off"></input>
</div>
</div>
<button type="submit" className="btn">Calculate BMI</button>
</form>
</div>
);
}
export default data_function;
As you can see App Component is the parent of Data Component. Whenever I fill out the form and hit submit, it triggers handlerFunction
which passes the data from
the Data Component to the App Component. The data which was sent to App Component is used to calculate the BMI and then the value of it is pushed into arrayBMI
(which is a state in App Component). I don't understand why after submitting it does not re-render the App Component.
Last 2 days i was probably trying to fix the problem which was caused by it. Today i discovered that my main App Component does not re-render when the value of any of the state changes and i have not idea why.