Skip to content

Commit

Permalink
fix(searchbox): handle Enter key in the input field to search + blur
Browse files Browse the repository at this point in the history
  • Loading branch information
lorumic committed Apr 18, 2024
1 parent 8a7d635 commit f4f011b
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/components/SearchBox/SearchBox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import classNames from "classnames";
import React, { HTMLProps, useRef } from "react";
import React, { HTMLProps, KeyboardEvent, useRef } from "react";

import Icon from "../Icon";

Expand Down Expand Up @@ -33,7 +33,7 @@ export type Props = PropsWithSpread<
*/
onChange?: (inputValue: string) => void;
/**
* A function that is called when the user clicks the search icon
* A function that is called when the user clicks the search icon or presses enter
*/
onSearch?: () => void;
/**
Expand Down Expand Up @@ -91,6 +91,13 @@ const SearchBox = React.forwardRef<HTMLInputElement, Props>(
onSearch && onSearch();
};

const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && internalRef.current.checkValidity()) {
internalRef.current.blur();
triggerSearch();
}
};

return (
<div className={classNames("p-search-box", className)}>
<label className="u-off-screen" htmlFor="search">
Expand All @@ -103,6 +110,7 @@ const SearchBox = React.forwardRef<HTMLInputElement, Props>(
id="search"
name="search"
onChange={(evt) => onChange?.(evt.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
ref={(input) => {
internalRef.current = input;
Expand Down

0 comments on commit f4f011b

Please sign in to comment.