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

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

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 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