Home > Software engineering >  Can you add onChange, onBlur and other events to children in React?
Can you add onChange, onBlur and other events to children in React?

Time:11-27

Is there a way to add additional functionality to children? Not just pass some state but pass actual event functions.

function FormField({ children }) {
  const [isFocused, setIsFocused] = useState(false);

  return (
    <FormGroup>
      {children}
      <Line />
    </FormGroup>
  );
}

CodePudding user response:

You can use React.Children.map to iterate children and use React.cloneElement to add additional props, including event handlers.

const onBlur = () => console.log('blur');

return (
  <FormGroup>
    {React.Children.map(
      children,
      c => React.cloneElement(c, { onBlur })
    )}
    <Line />
  </FormGroup>
);

CodePudding user response:

You can use React.cloneElement to add props to the children component you're getting, here's the example.

function FormField({ children }) {
  const [isFocused, setIsFocused] = useState(false);

  return (
    <FormGroup>
      {React.cloneElement(children,{
        onChange: yourFn
      })}
      <Line />
    </FormGroup>
  );
}
  • Related