Skip to content

Commit

Permalink
fix togle in dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
luzhnyak committed Mar 10, 2024
1 parent 5043b72 commit 0450421
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/components/Dropdown/Dropdown.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useEffect, useRef, useState } from "react";
import React, { useEffect, useRef, useState } from "react";

import css from "./Dropdown.module.css";
import Icon from "../Icon/Icon";

const ListDropdown = ({ items, onSelect, onClose }) => {
const ListDropdown = React.forwardRef(({ items, onSelect, onClose }, ref) => {
const listRef = useRef(null);

useEffect(() => {
Expand All @@ -14,7 +14,12 @@ const ListDropdown = ({ items, onSelect, onClose }) => {
};

const handleClose = (event) => {
if (listRef.current && !listRef.current.contains(event.target)) {
if (
listRef.current &&
!listRef.current.contains(event.target) &&
ref.current &&
!ref.current.contains(event.target)
) {
onClose(false);
}
};
Expand All @@ -40,12 +45,14 @@ const ListDropdown = ({ items, onSelect, onClose }) => {
</ul>
</div>
);
};
});

const Dropdown = ({ items = [], defaultSelect, onSelect }) => {
const [isOpenList, setIsOpenList] = useState(false);
const [selectText, setSelectText] = useState(defaultSelect);

const btnRef = useRef(null);

const handleSelect = (item) => {
onSelect(item);
setSelectText(item);
Expand All @@ -54,7 +61,13 @@ const Dropdown = ({ items = [], defaultSelect, onSelect }) => {

return (
<div className={css.wrapper}>
<button className={css.btn} onClick={() => setIsOpenList(!isOpenList)}>
<button
className={css.btn}
onClick={() => {
setIsOpenList(!isOpenList);
}}
ref={btnRef}
>
{selectText}
<Icon id="icon-dropdown" width="20" height="20" />
</button>
Expand All @@ -63,6 +76,7 @@ const Dropdown = ({ items = [], defaultSelect, onSelect }) => {
items={items}
onSelect={handleSelect}
onClose={() => setIsOpenList(false)}
ref={btnRef}
/>
)}
</div>
Expand Down

0 comments on commit 0450421

Please sign in to comment.