I'm toggling a component while clicking on div . It toogle down when clicked but does not close when clicked again what am i doing wrong?
export default function Shiva() {
const [loan, setLoan] = useState(false);
const handleClick = () => {
setLoan(true);
}
return (
<div className="">
<div className="">
<div className="loan-type-select" onClick={handleClick}>
<div className="">
<img src="" />
</div>
<p>SBA 7A Loan</p>
{loan ? <Data /> : '' }
</div>
</div>
</div>
Look closely at your click handler:
const handleClick = () => {
setLoan(true);
}
Regardless of the current state of loan, it will always set the new state of loan to true.
If you want to close it when it's open, toggle the current state instead of passing true.
const handleClick = () => {
setLoan(!loan);
}
I would like to add that instead of using:
setLoan(!loan)
It is better to use:
setLoan((preValue)=>{!preValue})
This way you make sure you won't face any issues (you are changing the previous value instead of changing the actual value).