0

I am trying to pass parent component click event to child and process all the form data in child itself and send back the data to parent.

I am using the material-ui multi-stepper form where my Next button is in Parent component and Forms are in child component. On click of Next get all the data from the form all in once in Parent rather than onEvery Input Change.

Parent Component (Index.js)

JSX Template

  <Button
      variant="contained"
      color="primary"
      onClick={handleNext}
      className={classes.button}>
     {activeStep === steps.length - 1 ? "Submit" : "Next"}
  </Button>

JS Code passing props to Child


  const [activeStep, setActiveStep] = React.useState(0);

  const handleNext = () => {
    setActiveStep(activeStep + 1);
  };

  const handleBack = () => {
    setActiveStep(activeStep - 1);
  };

  const detailsNextClick = detailsData => {
    console.log(detailsData);
  }

const getStepContent = (step) => {
  switch (step) {
      case 0:
        return <Details activeStep={activeStep} saveItem={detailsNextClick}/>;
      case 1:
        return <Address />;
      default:
        throw new Error("Unknown step");
    }

Child Component (Details.js)

Creating State Object for form

  const [values, setValues] = useState(DetailsInitialObj)

  const handleInputChange = ({ target }) => {
    const { name, value } = target;
    setValues({...values, [name]: value})
  };

  useEffect(() => {
      addItem()
  });

  const addItem = () => {
    if(props.activeStep !== 0){
      props.saveItem(values);
    }
  }

JSX Template of form

 <Grid container spacing={3}>
        <Grid item xs={12} sm={6}>
          <TextField
            required
            id="panNo"
            name="panNo"
            label="PAN No."
            fullWidth
            variant="outlined"
            margin="dense"
            onChange={handleInputChange}
            value={values.panNo}
            inputProps={{
              maxLength: 10
            }}
          />
        </Grid>

        <Grid item xs={12} sm={6}>
          <TextField
            required
            id="gstNo"
            name="gstNo"
            label="GSTIN No"
            fullWidth
            variant="outlined"
            margin="dense"
            onChange={handleInputChange}
            value={values.gstNo}
            inputProps={{
              maxLength: 40
            }}
          />
        </Grid>

So the flow should be like ....

Parent's Next Button ---> Process Form in Child itself ---> Return Form Data Object to Parent from Child Back

Deepak
  • 21
  • 1
  • 7

0 Answers0