Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Get the value of an input by clicking on a button

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>
  );
}
like image 552
MrFacundo Avatar asked Jan 24 '23 16:01

MrFacundo


2 Answers

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>
  );
}
like image 114
Zinho Avatar answered Feb 21 '23 10:02

Zinho


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>
  );
}
like image 24
KALITA Avatar answered Feb 21 '23 09:02

KALITA