Search code examples
javascriptreactjsreact-props

React use onChange from parent


I took over a project from a coworker that does not longer work for us. He has done things a bit different than I would have done it and now I'm pretty confused.

I have a parent component where I need to listen for changes made to the child and afterwards work with them in the parent component

Parent (I "obfuscated" props and fields due to company rules):

interface ParentProps {
  prop1: string;
  prop2?: string;
  prop3?: boolean;
}

function handleChange(value: String) {
  console.log(value);
}

export const Parent: FunctionComponent<ParentProps> = ({
  prop1,
  prop2,
  prop3 = isTrue(prop1),
}) => {
  return (
    <Children
      prop1Val={prop1}
      prop2Val={prop2}
      prop3Val={prop3}
      maskSettings={{
        mask: '##00 **** **** **** **** **** **** **** **',
        definitions: {
          '#': /[A-Z]/,
          '*': /[A-Z0-9]/,
        },
        prepare: (input: string) => input.toUpperCase(),
      }}
    >
    </Children>
  );
};

export default Parent;

Children:

import { IMaskMixin } from 'react-imask';
import {
  FormControl,
  TextField,
  TextFieldProps,
  FormHelperText,
} from '@material-ui/core';

type ChildrenInputComponentProps = ChildrenProps | TextFieldProps;

const InputComponent: FunctionComponent<TextFieldProps> = (props) => (
  <TextField {...props}/>
);

const ChildrenInputComponent: FunctionComponent<ChildrenInputComponentProps> = IMaskMixin(
  InputComponent
);

interface ChildrenInputProps {
  prop1: string;
  prop2?: string;
  prop3?: boolean;
  maskSettings: MaskProps;
}

export const Children: FunctionComponent<ChildrenInputProps> = ({
  prop1,
  prop2,
  prop3 = isTrue(prop1),
  maskSettings,
}) => (
        <div>
          <ChildrenInputComponent
            {...maskSettings}
            unmask={true}
            onAccept={(unmasked: string) =>
              !!!!!!!!
              
              use the handleChange from parent
              
              !!!!!!!!
            }
            InputLabelProps={{
              shrink: true,
            }}
            fullWidth
            label={prop2}
            required={prop3}
          />
          </div>
);

export default Children;

How would I access the handleChange in this situation? Thank you already!


Solution

  • You need to pass the handleChange from the parent to the child as props -

    <Children onChange={handleChange} ... />
    

    then call it in the child -

    onAccept={(unmasked: string) =>
       props.onChange(unmasked);
    }
    
    

    edit -

    you'll need to add onChange to your props object -

    export const Children: FunctionComponent<ChildrenInputProps> = ({
      prop1,
      prop2,
      prop3 = isTrue(prop1),
      maskSettings,
      onChange, // <!--- here
    }) => (
    

    then call it like -

    onAccept={(unmasked: string) =>
      onChange(unmasked);
    }