'Dynamic Select in Material UI, Formik and React with custom component

I would to populate the options of a Select component (made with Material UI) dynamically, which depends on the value of another Select component. I have created a custom component which I can reuse with Formik, and it looks like this -

const FormSelect = ({ name, data, ...otherProps }) => {
  // Get values for formik
  const { setFieldValue } = useFormikContext();
  const [field, meta] = useField(name);

  const handleChange = (event) => {
    const { value } = event.target;
    // Update formik state
    setFieldValue(name, value);
  };

  const config = {
    ...field,
    ...otherProps,
    select: true,
    variant: "outlined",
    fullWidth: true,
    onChange: handleChange,
  };

  // Error handling
  if (meta && meta.touched && meta.error) {
    config.error = true;
    config.helperText = meta.error;
  }

  return (
    <TextField {...config}>
      {data.map((item, index) => (
        <MenuItem key={index} value={item}>
          {item}
        </MenuItem>
      ))}
    </TextField>
  );
};

Here is my Form -

import * as React from "react";
import { Formik, Form } from "formik";
import { Grid, Typography } from "@mui/material";
import FormTextField from "./FormComponents/FormTextField";
import FormSelect from "./FormComponents/FormSelect";

<Form>
  <Grid container spacing={2}>
    <Grid item xs={12}>
      <Typography>Basic Information</Typography>
    </Grid>
  <Grid item xs={6}>
    <FormSelect
      name="sourceDatabase"
      label="Source Database"
      data={migrations}
    />
  </Grid>
  <Grid item xs={6}>
    <FormSelect
      name="targetDatabase"
      label="Target Database"
      data={migrations}
      disabled={true}
    />
  </Grid>
...

I would like to use the current value of sourceDatabase Component to populate what options to display in targetDatabase component, which are both Select components. I would also like to disable targetDatabase component if no value is selected for sourceDatabase. How can I achieve this functionality? Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source