diff --git a/src/components/SearchBox/SearchBox.test.tsx b/src/components/SearchBox/SearchBox.test.tsx index 7518fede0..198efc970 100644 --- a/src/components/SearchBox/SearchBox.test.tsx +++ b/src/components/SearchBox/SearchBox.test.tsx @@ -17,6 +17,25 @@ describe("SearchBox ", () => { ).toBeInTheDocument(); }); + it("shows and clears the button in uncontrolled mode", async () => { + const onChangeMock = jest.fn(); + render(); + + 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( , diff --git a/src/components/SearchBox/SearchBox.tsx b/src/components/SearchBox/SearchBox.tsx index 50b97c808..84d6dcef5 100644 --- a/src/components/SearchBox/SearchBox.tsx +++ b/src/components/SearchBox/SearchBox.tsx @@ -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"; @@ -86,7 +86,13 @@ const SearchBox = React.forwardRef( forwardedRef, ): React.JSX.Element => { const internalRef = useRef(null); + const [internalValue, setInternalValue] = useState(value ?? ""); + const hasValue = externallyControlled + ? Boolean(value) + : Boolean(internalValue); + const resetInput = () => { + setInternalValue(""); onChange?.(""); onClear?.(); if (internalRef.current) { @@ -119,7 +125,10 @@ const SearchBox = React.forwardRef( 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) => { @@ -136,7 +145,7 @@ const SearchBox = React.forwardRef( value={externallyControlled ? value : undefined} {...props} /> - {value && ( + {hasValue && (