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

219
Vistas
Trim all values of the input by default

I have a reusable Input built on top-of Antd Input.

Now I have a prop trim which is a boolean.

If trim is true, we trim the leading and trailing white spaces as below.

export default function MyInput({ trim, onChange, ...props }) {
  const handleChange = (e) => {
    if (trim) {
      e.target.value = e.target.value.trim();
    }
    onChange?.(e);
  };

  return <Input onChange={handleChange} {...props} />;
}

This works completely fine.

Code available here

But is it a good approach?

If not what's the better alternative for achieving this functionality?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is not a good approach. it defeats the purpose of React working with the Virtual DOM. Avoid manipulating the DOM directly when using React. A good solution will be using a state to store the input, and feed the state back into the input using value property.

Review the code below:

export default function MyInput({ trim, onChange, ...props }) {
    const [input, setInput] = React.useState("");
    const handleChange = (e) => {
        if (trim) {
            setInput(e.target.value.trim());
        } else {
            setInput(e.target.value);
        }
        onChange?.(e);
     };

     return <Input onChange={handleChange} value={input} {...props} />;
}

With this approach, you are letting React manage the input for you, and you can read the input at any time using the state. You may want to pass the input state to your props.onChange.

about 4 years ago · Juan Pablo Isaza 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