Home > OS >  React Send Data from Child to Parent with Typescript
React Send Data from Child to Parent with Typescript

Time:05-04

I am trying to send data from Child Component to Parent component, using Typescript. There are lot of resources, but many don't explore typescript concept.

On the Parent, how would I set the ProductType event? Is this the proper way using React.ChangeEvent? We are using a dropdown selector with Material UI.

onProductTypeChange={(e: React.ChangeEvent<HTMLInputElement>) =>
         setProductType(e.target.value)}

Full Code:

Parent:

const ProductExport = () => {
 const [productType, setProductType] = useState<undefined | string>('');

 return (
 <>
 <ProductFilters
      productTypeValue={productType}
      onProductTypeChange={(e: React.ChangeEvent<HTMLInputElement>) =>
         setProductType(e.target.value)}
 />

Child:

type Props = {
  productTypeValue?: string;
  onProductTypeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
};

const ProductFilters = ({
  productTypeValue,
  onProductTypeChange
}: Props) => {
  return (
    <Box>
      <Accordion>
        <AccordionSummary>
          <Typography>Products</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Box >
            <Box>
              <TextField
                select
                value={productTypeValue}
                onChange={onProductTypeChange}
                label={'Select Product Type'}
              >

CodePudding user response:

Usually you hide the internal details in the Child (the actual event), and expose to the parent only the result (new data):

// Parent
const ProductExport = () => {
 const [productType, setProductType] = useState<undefined | string>('');

 return (
   <ProductFilters
      productTypeValue={productType}
      onProductTypeChange={setProductType}
   />
  );
}

// Child
type Props = {
  productTypeValue?: string;
  onProductTypeChange?: (newType: string) => void;
};

const ProductFilters = ({
  productTypeValue,
  onProductTypeChange
}: Props) => {
  return (
    <TextField
      select
      value={productTypeValue}
      onChange={(event) => onProductTypeChange?.(event.target.value)}
      label={'Select Product Type'}
    />
  );
}

CodePudding user response:

React has a preprepared type for multiple event handlers, such ChangeEventHandler (TS playground):

type Props = {
  productTypeValue?: string;
  onProductTypeChange: ChangeEventHandler<HTMLInputElement>;
};

const ProductFilters = ({
  productTypeValue,
  onProductTypeChange
}: Props) => null;

const ProductExport = () => {
  const [productType, setProductType] = useState<undefined | string>('');

  const onProductTypeChange: ChangeEventHandler<HTMLInputElement> = e => setProductType(e.target.value);

  return (
    <ProductFilters
      productTypeValue={productType}
      onProductTypeChange={onProductTypeChange}
    />
  );
};
  • Related