0

I am working on a component where the user searches a term and it is returned to them through a filter. I am using useContext hook to pass data from db via axios. I would like to use the button in the CompSearch component to render the results rather than having them show up on a keystroke. My question is how do I render the results via button click?

Here is the code

Julie
  • 484
  • 7
  • 22

2 Answers2

2

Follow these steps to achieve that.

  1. Change the input element into an uncontrolled component.
  2. Get the value using reference in React.
import React, { useContext, useRef, useState } from "react";
import CompanyInfoList from "./CompanyInfoList";
import { CompListContext } from "./CompListContext";

const CompSerach = () => {
  const [company, setCompany] = useContext(CompListContext);
  const [searchField, setSearchField] = useState("");
  const [searchShow, setSearchShow] = useState(false);

  const filtered = company.filter((res) => {
    return res.company.toLowerCase().includes(searchField.toLowerCase());
  });

  const inputRef = useRef(null); // 1. Create the ref

  const handleClick = () => {
    const val = inputRef.current.value; // 3. Get the value
    setSearchField(val);

    if (val === "") {
      setSearchShow(false);
    } else {
      setSearchShow(true);
    }
  };

  const searchList = () => {
    if (searchShow) {
      return <CompanyInfoList filtered={filtered} />;
    }
  };

  return (
    <>
      <div>
        <em>
          NOTE: if you search "ABC" or "EFGH" you will see results - my goal is
          to see those results after clicking button
        </em>
        <br />
        <input
          type="search"
          placeholder="search Company Title"
          ref={inputRef} {/* 2. Assign the ref to the Input */}
        />
        <button onClick={handleClick}>Enter</button>
      </div>
      {searchList()}
    </>
  );
};

export default CompSerach;

https://codesandbox.io/s/show-on-button-click-68157003-rot6o?file=/src/TestTwo/CompSearch.js

Let me know if you need further support.

Yushan
  • 1,029
  • 1
  • 9
  • 12
1
const handleChange = (e) => {
    setSearchField(e.target.value);
    if (e.target.value === "") {
      setSearchShow(false);
    } else {
      setSearchShow(true);
    }
    **setCompany(e.target.value);**
  };

i think your question is similar with autocomplete.

kingpanda419
  • 121
  • 2