I created an event listener for an Autocomplete component from the Mantine UI library in order to listen for keydown events and navigate to a new page for search results. Unfortunately, whenever I click on the component and type a key (in other words, when the keydown event fires), the input loses focus. I'd like to know how to prevent this while preserving the current behavior of my component, as everything else is working as expected.
function SearchComponent(props: {
searchQuery;
setSearchQuery;
essayTitleArray;
}) {
// Define an event listener callback function
const handleKeyDown = useCallback((event) => {
if (event.key === "Enter") {
navigate({
pathname: "/",
search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
});
}
}, []);
// Add the event listener
const ref = useEventListener("keydown", handleKeyDown);
return (
<Autocomplete
ref={ref}
value={searchQuery}
radius={"md"}
onChange={(event: string) => {
setSearchQuery(event);
}}
className={classes.search}
placeholder="Search"
icon={<IconSearch size={16} stroke={1.5} />}
data={essayTitleArray}
limit={4}
onItemSubmit={(item) => {
navigate({
pathname: "/compose",
search: `?${createSearchParams({ essayId: item.key })}`,
});
}}
/>
);
}
Relevant variables/hooks
const [searchQuery, setSearchQuery] = useState("");
const [essayTitleArray, setEssayTitleArray] = useState([]);
const navigate = useNavigate();
The state variables here are declared and populated elsewhere, they work fine.
import { createSearchParams, useNavigate } from "react-router-dom";
import { useEventListener } from "@mantine/hooks";
import React, { useCallback, useEffect, useRef, useState } from "react";
I tried to use event.preventDefault() in an else block in the handleKeyDown callback function of my code, which stopped the component from losing focus but also stopped me from being able to enter text into the input. Similarly, I tried using event.stopPropagation() in the same place, but it didn't seem to do anything.
function SearchComponent(props: {
searchQuery;
setSearchQuery;
essayTitleArray;
}) {
// Define an event listener callback function
const handleKeyDown = useCallback((event) => {
if (event.key === "Enter") {
navigate({
pathname: "/",
search: `?${createSearchParams({ searchQuery: props.searchQuery })}`,
});
} else {
event.preventDefault();
}
}, []);
// Add the event listener
const ref = useEventListener("keydown", handleKeyDown);
return (
<Autocomplete
ref={ref}
value={searchQuery}
radius={"md"}
onChange={(event: string) => {
setSearchQuery(event);
}}
className={classes.search}
placeholder="Search"
icon={<IconSearch size={16} stroke={1.5} />}
data={essayTitleArray}
limit={4}
onItemSubmit={(item) => {
navigate({
pathname: "/compose",
search: `?${createSearchParams({ essayId: item.key })}`,
});
}}
/>
);
}