i have a simple app with a single value, 2 buttons and 3 divs. The value variable starts at 0, the buttons either increases or decrease the value, i have 3 divs; small, medium & large. i need to render a div based on the value. if the value is 20, the large div, value less than or equal to 10, medium div, if less than 10, small div.
My goal here is to render a view based on an input from the user.
Here is my code
import React, { useState, useEffect } from 'react';
const ShowHide = () => {
const [value, setValue] = useState(0);
const [lrg, setLrg] = useState(false);
const [mid, setMid] = useState(false);
const [sml, setSml] = useState(true);
if (value >= 20 ) {
setLrg(true)
setMid(false)
setSml(false)
}
if ( value >= 10 && value <= 20) {
setLrg(false)
setMid(true)
setSml(false)
}
if (value < 10 ) {
setLrg(false)
setMid(false)
setSml(true)
}
return <>
<h3>show/hide div</h3>
<div>
<h3> value is :{value}</h3>
<button className='btn' onClick={() => {setValue(value + 5)}}> add </button>
<br></br>
<button className='btn' onClick={() => {setValue(value - 5)}}> minus </button>
</div>
<br></br>
<div className="form">
{lrg && <Lrg />}
{mid && <Mid />}
{sml && <Sml />}
</div>
</>;
};
const Lrg = () => {
return (
<div>
<h3> value is larger than 20</h3>
</div>
);
}
const Mid = () => {
return (
<div>
<h3> value is btwn 10 and 20</h3>
</div>
);
}
const Sml = () => {
return (
<div>
<h3> value is less than 10</h3>
</div>
);
}
export default ShowHide;
To make it work, i have defined 3 other variables, sml, med, lrg. that start at false for lrg and med since the value starts at 0, and true for sml since value is 0. when the values change, i want to update these var accordingly. however i get this error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
It comes after i add the if else statements, how do i create some conditions without that error