Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda