goyat
goyat

Reputation: 59

Passing onChange from parent overides onChange of the child component - React

Let's say I have an Input component with onChange event handler in it, say count input characters(just to illustrate there's a build-in functionality in that component that I want to use no matter what) and I want to use this Input like across all of my other components:

const Input = (props) => {
  const { name, value, countLimit, ...restProps } = props;
  const [count, setCount] = useState(0);

  const countCharacters = (e) => {
    setCount(e.currentTarget.value.length);
  };

  return (
    <div>
      <input
        name={name}
        value={value}
        onChange={countCharacters}
        {...restProps}
      />
      <br />
      Count: {count} / {countLimit}
    </div>
  );
};

The problem though, is that if I want to pass an onChange event handler from outside this component, say to grab some input's value or pass some data from child to parent or something else, it will override this countCharacters one. What is the best way to deal with this kind of scenarios?

Upvotes: 1

Views: 781

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51886

Invoke props.onChange (if it exists) from within countCharacters:

const Input = (props) => {
  const { name, value, countLimit, onChange, ...restProps } = props;
  const [count, setCount] = useState(0);

  const countCharacters = (e) => {
    setCount(e.currentTarget.value.length);
    onChange?.(e);
  };

  return (
    <div>
      <input
        name={name}
        value={value}
        onChange={countCharacters}
        {...restProps}
      />
      <br />
      Count: {count} / {countLimit}
    </div>
  );
};

Upvotes: 2

Related Questions