Skip to content
Merged
Show file tree
Hide file tree
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
19 changes: 19 additions & 0 deletions src/components/SearchBox/SearchBox.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@ describe("SearchBox ", () => {
).toBeInTheDocument();
});

it("shows and clears the button in uncontrolled mode", async () => {
const onChangeMock = jest.fn();
render(<SearchBox onChange={onChangeMock} />);

const searchInput = screen.getByRole("searchbox");
await userEvent.type(searchInput, "admin");

const clearButton = screen.getByRole("button", { name: Label.Clear });
expect(clearButton).toBeInTheDocument();

await userEvent.click(clearButton);

expect(searchInput).toHaveValue("");
expect(onChangeMock).toHaveBeenLastCalledWith("");
expect(
screen.queryByRole("button", { name: Label.Clear }),
).not.toBeInTheDocument();
});

it("can externally control the value", () => {
const { rerender } = render(
<SearchBox externallyControlled onChange={jest.fn()} value="admin" />,
Expand Down
15 changes: 12 additions & 3 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, KeyboardEvent, useRef } from "react";
import React, { HTMLProps, KeyboardEvent, useRef, useState } from "react";

import Icon from "../Icon";

Expand Down Expand Up @@ -86,7 +86,13 @@ const SearchBox = React.forwardRef<HTMLInputElement, Props>(
forwardedRef,
): React.JSX.Element => {
const internalRef = useRef<HTMLInputElement>(null);
const [internalValue, setInternalValue] = useState(value ?? "");
const hasValue = externallyControlled
? Boolean(value)
: Boolean(internalValue);

const resetInput = () => {
setInternalValue("");
onChange?.("");
onClear?.();
if (internalRef.current) {
Expand Down Expand Up @@ -119,7 +125,10 @@ const SearchBox = React.forwardRef<HTMLInputElement, Props>(
disabled={disabled}
id={id}
name={name}
onChange={(evt) => onChange?.(evt.target.value)}
onChange={(evt) => {
setInternalValue(evt.target.value);
onChange?.(evt.target.value);
}}
onKeyDown={onKeyDown}
placeholder={placeholder}
ref={(input) => {
Expand All @@ -136,7 +145,7 @@ const SearchBox = React.forwardRef<HTMLInputElement, Props>(
value={externallyControlled ? value : undefined}
{...props}
/>
{value && (
{hasValue && (
<button
className="p-search-box__reset"
disabled={disabled}
Expand Down