I need to implement a search button that searches the value of an input. I know how to add an onClick listener (is that the name?) to the button so that it fires (is that the expresion?) a function.
But within the function, I don't know how to get the input value.
Here's what I got:
function App() {
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
const { jobs, loading, error } = useFetchJobs(query, page)
function handleSearch(e) {
setQuery(???)
setPage(1)
}
return (
<Container className="my-4">
<input type="text"></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
Here's what I've tried. A line of code I found on google. I get Error: Function components cannot have string refs
function App() {
function handleSearch(e) {
setQuery(React.findDOMNode(this.refs.search).value.trim())
setPage(1)
}
return (
<Container className="my-4">
<input type="text" ref="search" ></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
What you can do is to create a handleChange on input, and every time the input changes, the state changes... so on you run the handleSubmit, you only have to get the state
function App() {
const [inputValue, setInputValue] = useState('')
function handleSearch(e) {
// here you can get the inputValue
DoWhateverIWantWithSearchValue(inputValue)
}
return (
<Container className="my-4">
<input type="text" handleChange={(e) => setInputValue(e.target.value)} ></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
First set the value of the input to query(initial value will be null as we set that in useState) then on changing the value of the input we set value of the input to setQuery using onChange method, now you can use the query value to search
function App() {
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
const { jobs, loading, error } = useFetchJobs(query, page)
function handleSearch(e) {
\\**write your search function here with query value**
}
return (
<Container className="my-4">
<input value={query} onChange={(e)=>setQuery(e.target.value)} type="text"></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With