Search code examples
reactjsreact-dom

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>
  );
}

Solution

  • 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>
      );
    }