Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!