Trim all values of the input by default

Viewed 37

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?

1 Answers

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.

Related