score:2

Accepted answer
const NOP = () => {};
const DEFAULT_INPUT = "";

function SearchTermBar(props) {
  const { resetStateSearchTerm = NOP, handlePowerToggleParent = NOP } = props;
  const inputRef = useRef();

  useEffect(() => {
    const keyPressEvent = (e) => {
      if (e.keyCode === 13) {
        resetStateSearchTerm(inputRef.current.value);
        inputRef.current.value = DEFAULT_INPUT;
        handlePowerToggleParent("search");
      }
    };

    inputRef.current.addEventListener("keydown", keyPressEvent);
    let parentInputRef = inputRef;

    return () => {
      console.log("remove event listener");
      parentInputRef.current.removeEventListener("keydown", keyPressEvent);
    };
  }, [resetStateSearchTerm, handlePowerToggleParent]);

  return (
    <input
      type="text"
      placeholder="Enter search term here (Press return to confirm)"
      style={{ width: "50%" }}
      ref={inputRef}
    />
  );
}

Related Query

More Query from same tag