So I am creating a custom searchbox that has a reset
button for clearing the searchbox value. But the reset button to be hidden if the searchbox is empty then will only be visible on keyup
event. But I have no idea how to incorporate this on React JS. Here is my code
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { useEffect, useState } from 'react';
import { Button, Container, Form, Navbar } from "react-bootstrap";
import { Link } from "react-router-dom";
export default function AppNavbar() {
const [search, setSearch] = useState("");
useEffect(() => {
if (search !== '') {
console.log(search);
}
});
return (
<Navbar bg="accent-1" expand="lg" className='py-3'>
<Container>
<Navbar.Brand as={Link} to="/" className="m-0 p-0 lh-1">Project</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Form className="mx-0 mx-lg-5 d-flex flex-fill justify-content-center" role="search">
<Form.Group className="input-group" id="searchbox" controlId="prodSearch">
<Form.Control type="search" name="prodSearch" className="searchbox border-accent" placeholder="Search for products" maxLength={75} aria-label="Search for products" aria-describedby="button-search" onKeyUp={e => setSearch(e.target.value)} />
<Button type="reset" variant="text" className="clear-search hidden"><FontAwesomeIcon icon="fa-solid fa-xmark" /></Button>
<Button type="submit" id="button-search" variant="search" className="px-4 bg-accent-2"><FontAwesomeIcon icon="fa-solid fa-magnifying-glass" /></Button>
</Form.Group>
</Form>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
Right now I just have a console log for when you type something on the searchbox. What I want is the button reset to change classname from hidden
to show
becuase in my css, I have this
.navbar .input-group .clear-search.show {
display: block;
}
.navbar .input-group .clear-search.hidden {
display: none;
}
which will, supposedly, make it visible or hidden. I just don’t know how to access the button reset element for when on keyup event. Any ideas?
2
Answers
Its okay I finally got it! I just utilized useState for detecting changes then created conditional statement in the className of the button.
You don’t need a keyup event. You should control your display based on the state of the component.
I’d suggest using the search input text as the control for this. When there is search text, show the reset, otherwise, don’t.
For this you need an onChange handler for the input text to store it in state.