0
votes

I'm trying to use the MUI toggle group with React Hook Form however I can't get the value to post when submitting the form. My toggle group component looks like this:

import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter';
import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';
import FormatAlignRightIcon from '@material-ui/icons/FormatAlignRight';
import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import React from 'react';
import {Controller} from "react-hook-form";

export default function TestToggleGroup(props) {
  const {control} = props;
  const [alignment, setAlignment] = React.useState('left');

  const handleAlignment = (event) => {
    setAlignment(event[1]);
  };

  return (
      <Controller
          name="ToggleTest"
          as={
            <ToggleButtonGroup
                value={alignment}
                exclusive
                onChange={handleAlignment}
                aria-label="text alignment"
            >
              <ToggleButton value="left" aria-label="left aligned" key="left">
                <FormatAlignLeftIcon/>
              </ToggleButton>
              <ToggleButton value="center" aria-label="centered" key="center">
                <FormatAlignCenterIcon/>
              </ToggleButton>
              <ToggleButton value="right" aria-label="right aligned" key="right">
                <FormatAlignRightIcon/>
              </ToggleButton>
              <ToggleButton value="justify" aria-label="justified" disabled key="justify">
                <FormatAlignJustifyIcon/>
              </ToggleButton>
            </ToggleButtonGroup>
          }
          value={alignment}
          onChange={(e) => {
            handleAlignment(e);
          }}
          valueName={"alignment"}
          control={control}
      />
  );
}

Not sure exactly what I'm doing wrong but any assistance would be greatly appreciated.

1

1 Answers

1
votes

My workaround was using an effect to manually set the value using setValue and then using getValues() inside your handleSubmit function to get the values.

const { control, setValue } = props;

//Effect
React.useEffect(() => {
  setAlignment('ToggleTest', alignment);
}, [alignment, setAlignment]);