Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(searchbox): handle Enter key in the input field to search + blur #1065

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should stop blur when the input contains an invalid value (#1065 (comment))

internalRef.current.blur();
triggerSearch();
lorumic marked this conversation as resolved.
Show resolved Hide resolved
}
};

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
Loading