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

162
Vistas
Why can't I append a child using useState in React?

I am using React and found something which was not quite working, but it made sense to me totally:

const [Res, setRes] = useState(<div></div>);
const test = (e) => {
    if (e.keyCode === 13) {
      setRes( prevState => prevState.append(<p>{e.target.value)}</p>))
    }
  }
return(
    {Res}
)

If this us wrong, please tell me the correct way to solve similar problems please.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Keeping JSX in state is an antipattern.

Instead of keeping the JSX in an array in state, keep the data in the array without JSX, then build the JSX when you are ready to render:

const YourComponent = () => {
  const [res, setRes] = useState([]);

  const test = (e) => {
    const {value} = e.target;

    if (e.code === "Enter") {
      setRes(prev => [...prev, value]);
    }
  };

  return (
    <div>
      {res.map(e => <p>{e}</p>)}
    </div>
  );
};

<p> is using index as key, which is a problem. How to fix it is application-specific depending on where your data is coming from and whether it can be removed from the array, whether it's unique, etc, but ideally generate an id.

Also, e.target.value shouldn't be accessed in a state setter callback. It's async so the event object might have gone stale by the time it's read. Pull out the primitive value into the handler closure.

I suggest picking better names: test and res are pretty meaningless.

Finally, instead of e.keyCode === 13, use e.code === "Enter".

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