diff --git a/playbook/app/pb_kits/playbook/pb_dropdown/_dropdown.tsx b/playbook/app/pb_kits/playbook/pb_dropdown/_dropdown.tsx index 5940e22e29..27234c3fec 100644 --- a/playbook/app/pb_kits/playbook/pb_dropdown/_dropdown.tsx +++ b/playbook/app/pb_kits/playbook/pb_dropdown/_dropdown.tsx @@ -1,4 +1,4 @@ -import React, { useState, useRef, useEffect } from "react"; +import React, { useState, useRef, useEffect, forwardRef, useImperativeHandle } from "react"; import classnames from "classnames"; import { buildAriaProps, buildCss, buildDataProps, buildHtmlProps } from "../utilities/props"; import { globalProps } from "../utilities/globalProps"; @@ -38,7 +38,14 @@ type DropdownProps = { triggerRef?: any; }; -const Dropdown = (props: DropdownProps) => { +interface DropdownComponent + extends React.ForwardRefExoticComponent> { + Option: typeof DropdownOption; + Trigger: typeof DropdownTrigger; + Container: typeof DropdownContainer; +} + +const Dropdown = forwardRef((props: DropdownProps, ref: any) => { const { aria = {}, autocomplete = false, @@ -125,7 +132,7 @@ const Dropdown = (props: DropdownProps) => { const filteredOptions = optionsWithBlankSelection?.filter((option: GenericObject) => { const label = typeof option.label === 'string' ? option.label.toLowerCase() : option.label; return String(label).toLowerCase().includes(filterItem.toLowerCase()); - }); + }); // For keyboard accessibility: Set focus within dropdown to selected item if it exists useEffect(() => { @@ -175,6 +182,14 @@ const Dropdown = (props: DropdownProps) => { dark }); + useImperativeHandle(ref, () => ({ + clearSelected: () => { + setSelected({}); + setFilterItem(""); + setIsDropDownClosed(true); + onSelect && onSelect(null); + }, + })); return (
{
) -}; +}) as DropdownComponent +Dropdown.displayName = "Dropdown"; Dropdown.Option = DropdownOption; Dropdown.Trigger = DropdownTrigger; Dropdown.Container = DropdownContainer; diff --git a/playbook/app/pb_kits/playbook/pb_dropdown/docs/_dropdown_clear_selection.jsx b/playbook/app/pb_kits/playbook/pb_dropdown/docs/_dropdown_clear_selection.jsx new file mode 100644 index 0000000000..eeece1ec52 --- /dev/null +++ b/playbook/app/pb_kits/playbook/pb_dropdown/docs/_dropdown_clear_selection.jsx @@ -0,0 +1,45 @@ +import React, { useRef } from 'react' +import { Button, Dropdown } from 'playbook-ui' + +const options = [ + { + label: "United States", + value: "United States", + }, + { + label: "Canada", + value: "Canada", + }, + { + label: "Pakistan", + value: "Pakistan", + } +] + +const DropdownClearSelection = (props) => { + const dropdownRef = useRef(null) + + const handleReset = () => { + if (dropdownRef.current) { + dropdownRef.current.clearSelected() + } + } + + return ( + <> + +