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(ExpandableSearch): allow isExpanded state to be controlled #15544

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import React, { useState, useRef } from 'react';
import React, { useState, useRef, useEffect } from 'react';
import classnames from 'classnames';
import Search, { type SearchProps } from '../Search';
import { usePrefix } from '../../internal/usePrefix';
Expand All @@ -31,11 +31,15 @@ function ExpandableSearch({
evt.relatedTarget &&
evt.relatedTarget.classList.contains(`${prefix}--search-close`);

if (expanded && !relatedTargetIsAllowed && !hasContent) {
if (expanded && !relatedTargetIsAllowed && !hasContent && !isExpanded) {
setExpanded(false);
}
}

useEffect(() => {
setExpanded(!!isExpanded);
}, [isExpanded]);

function handleChange(evt) {
setHasContent(evt.target.value !== '');
}
Expand All @@ -50,7 +54,7 @@ function ExpandableSearch({
evt.stopPropagation();

// escape key only clears if the input is empty, otherwise it clears the input
if (!evt.target?.value) {
if (!evt.target?.value && !isExpanded) {
setExpanded(false);
}
}
Expand Down
19 changes: 18 additions & 1 deletion packages/react/src/components/Search/Search.stories.js
Expand Up @@ -5,12 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import React, { useState, useCallback } from 'react';

import { WithLayer } from '../../../.storybook/templates/WithLayer';

import ExpandableSearch from '../ExpandableSearch';
import Search from '.';
import Button from '../Button';

export default {
title: 'Components/Search',
Expand All @@ -27,6 +28,22 @@ export default {
},
};

export const Test = () => {
const [isExpanded, setExpanded] = useState(false);

const handleToggleExpandClick = useCallback(() => {
setExpanded(!isExpanded);
}, [isExpanded]);

return (
<>
<div>isExpanded = {isExpanded.toString()}</div>
<ExpandableSearch isExpanded={isExpanded} />
<Button onClick={handleToggleExpandClick}>Toggle Expand</Button>
</>
);
};

export const Default = () => (
<Search
size="lg"
Expand Down