Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
How to position an element to a selected anchor without giving rendering each anchor's content for each anchor?

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?

tender-margulis-cjil0b

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>
  );
});

Code sandbox

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!