Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda