I need to open a very simple search bar in reactjs, and there is no closing button because I want to click on the same button to close it.
Here is some code I tried out but didn't work.
const [searchIsOpen, setSearchIsOpen] = useState(false);
const search = () => {
if (searchIsOpen) {
setSearchIsOpen(true);
} else {
setSearchIsOpen(false);
}
};
<button onClick={search}
className="absolute md:left-8 left-3 lg:left-2 top-6 md:top-8 cursor-pointer">
</button>
And this element should open.
<div>
<input type="text" name="" id="" />
</div>
thank you.
CodePudding user response:
You should use conditional rendering.
const [searchIsOpen, setSearchIsOpen] = useState(false);
const search = () => {
setSearchIsOpen(!searchIsOpen);
};
<button onClick={search} className="absolute md:left-8 left-3 lg:left-2 top-6 md:top-8 cursor-pointer"></button>
{
searchIsOpen && <div>
<input type="text" name="" id="" />
</div>
}
CodePudding user response:
<div>
{ searchIsOpen && <input type="text" name="" id="" /> }
</div>