From fcabb0b76129e9f0e42026fa323a64e5dd1e8319 Mon Sep 17 00:00:00 2001 From: Ariella Gilmore Date: Wed, 16 Mar 2022 14:16:04 -0700 Subject: [PATCH] fix(masthead-search): react searchNoRedirect prop doesn't work on enter (#8516) ### Related Ticket(s) #8334 ### Description people using the `searchNoRedirect` prop and press enter within the search box are still being redirected. The `onKeyDown` was removed in this [PR](https://github.com/carbon-design-system/carbon-for-ibm-dotcom/pull/7365), but it is actually necessary when the `searchNoRedirect` is used ### Changelog **New** - added back the `onKeyDown` function (cherry picked from commit a176c21b8509eb2c2bf72c1a779f8a4f36f1d419) --- .../__snapshots__/storyshots.test.js.snap | 2 ++ .../src/components/Masthead/MastheadSearch.js | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/packages/react/src/__tests__/__snapshots__/storyshots.test.js.snap b/packages/react/src/__tests__/__snapshots__/storyshots.test.js.snap index f86b1339853..d2a2a8d9197 100644 --- a/packages/react/src/__tests__/__snapshots__/storyshots.test.js.snap +++ b/packages/react/src/__tests__/__snapshots__/storyshots.test.js.snap @@ -52869,6 +52869,7 @@ exports[`Storyshots Components|Dotcom shell Search open 1`] = ` "aria-label": "Search all of IBM", "className": "bx--header__search--input", "onChange": [Function], + "onKeyDown": [Function], "placeholder": "Search all of IBM", "role": "combobox", "value": "", @@ -123762,6 +123763,7 @@ exports[`Storyshots Components|Masthead Search open onload 1`] = ` "aria-label": "Search all of IBM", "className": "bx--header__search--input", "onChange": [Function], + "onKeyDown": [Function], "placeholder": "Search all of IBM", "role": "combobox", "value": "", diff --git a/packages/react/src/components/Masthead/MastheadSearch.js b/packages/react/src/components/Masthead/MastheadSearch.js index 87fe1cbe575..03bf628832a 100755 --- a/packages/react/src/components/Masthead/MastheadSearch.js +++ b/packages/react/src/components/Masthead/MastheadSearch.js @@ -270,6 +270,27 @@ const MastheadSearch = forwardRef( event.currentTarget.dispatchEvent(onSearchNoRedirect); } + /** + * Custom onKeyDown event handlers + * + * @param {event} event The callback event + */ + function onKeyDown(event) { + switch (event.key) { + case 'Enter': { + // Disables Enter key if searchNoRirect is true + if (rest.searchNoRedirect) { + onSearchNoRedirect(event, state.val); + event.preventDefault(); + } + // Disable search on enter key if the search field is empty + if (!state.val) { + event.preventDefault(); + } + } + } + } + /** * When the input field changes, we set the new val to our state * @@ -296,6 +317,7 @@ const MastheadSearch = forwardRef( placeholder: placeHolderText, value: state.val, onChange, + onKeyDown, className: `${prefix}--header__search--input`, 'aria-label': placeHolderText, role: 'combobox',