Passing data child to parent functional components in reactjs

Suppose the state drive needs to be present in the Parent and the Child. Then you define it in the parent and create a callback function responsible for changing this state setDrive.

In general, the state must be defined at closest common ancestor between the components that use or change this state and this is called Lifting State Up. In your case, something like this (complete demo):

Parent:

const VehicleList = () => {
  const classes = useStyles();
  const [drive, setDrive] = React.useState(null); // the lifted state

  const sendDataToParent = (index) => { // the callback. Use a better name
    console.log(index);
    setDrive(index);
  };

  return (
    <div className={classes.root}>
      {vehicleData.map((vehicle) => (
        <div
          key={vehicle.name}
          style={{
            width: "20rem",
            border: vehicle.name === drive ? "1px solid red" : null
          }}
        >
          <Vehicle vehicle={vehicle} sendDataToParent={sendDataToParent} />
        </div>
      ))}
    </div>
  );
};

Child:

const Vehicle = ({ vehicle, sendDataToParent }) => {
  const classes = useStyles();
  const [showDriveAction, setShowDriveAction] = React.useState(false);
  const driveURL = React.useState("");

  return (
    <Paper className={classes.root} elevation={3}>
      <Grid container spacing={2}>
        {/* ... */}
        <CardActions>
          <Button
            onClick={() => {
              sendDataToParent(vehicle.name);
            }} //this is where it needs to be passed
            size="small"
            color="secondary"
            startIcon={<FolderOpenIcon />}
            style={{ fontWeight: "bold" }}
          >
          {/* ... */}
        </CardActions>
      </Grid>
    </Paper>
  );
};

Leave a Comment

tech