I have a list of items (anchors) and every time an element is selected, I want to render a component (a color picker) just under it:
import * as React from "react";
import clsx from "clsx";
import "./styles.css";
interface DropDownProps {
index: number;
}
const DropDown: React.FC<DropDownProps> = React.memo(({ index }) => (
<div className="dropdown">dropdown for anchor {index}</div>
));
export default React.memo(() => {
const [selected, setSelected] = React.useState<null | number>(null);
const handleSelect = React.useCallback(
(index: number) => () => {
setSelected(index);
},
[]
);
return (
<div className="wrapper">
{Array.from({ length: 3 }, (_, index) => {
return (
<div
className={clsx("anchor", { selected: selected === index })}
onClick={handleSelect(index)}
>
anchor {index} ↓{selected === index && <DropDown index={index} />}
</div>
);
})}
</div>
);
});
The problem is that the Array.from expands to:
<div className={clsx("anchor", { selected: selected === 0 })}>
{'anchor 0 ↓'}
{selected === 0 && <DropDown index={0} />}
</div>
<div className={clsx("anchor", { selected: selected === 1 })}>
{'anchor 1 ↓'}
{selected === 1 && <DropDown index={1} />}
</div>
<div className={clsx("anchor", { selected: selected === 2 })}>
{'anchor 2 ↓'}
{selected === 2 && <DropDown index={2} />}
</div>
I'd like the DropDown component to somehow be 'portaled' to whichever element is currently selected, instead of being conditionally rendered based on the value of selected. How can I do this?
You can achieve this by giving the selected div an id, which we will use to portal the dropdown to. To do this we will useRef to retrieve and store the element with the id. Since the id will only be assigned in the rerender after the selection, we add an useEffect to update the ref after the selection changed, while using a dummy useState to force another update (since setting the value of a ref does not cause rerenders). Then the dropdown will appear below the correct item.
export default React.memo(() => {
const [selected, setSelected] = React.useState<null | number>(null);
const ref = React.useRef<HTMLElement | null>(null);
const [_, forceUpdate] = React.useState(0);
const handleSelect = React.useCallback(
(index: number) => () => {
setSelected(index);
},
[]
);
React.useEffect(() => {
ref.current = document.getElementById("selected");
forceUpdate((prev) => prev + 1);
}, [selected]);
return (
<div className="wrapper">
{Array.from({ length: 3 }, (_, index) => {
return (
<div
id={selected === index ? "selected" : ""}
className={clsx("anchor", { selected: selected === index })}
onClick={handleSelect(index)}
>
anchor {index}
</div>
);
})}
{selected !== null &&
!!ref.current &&
ReactDOM.createPortal(<DropDown index={selected} />, ref.current)}
</div>
);
});