简体   繁体   中英

Setting Default values for MUI toggle button group

I am using the Material UI library, and used the button toggle widget as a picker.

Here is my codesandbox - https://codesandbox.io/s/50pl0jy3xk

There are a few interactions going on, but basically a user can click a membership type for an adult, child or infant. There are 3 options of yes, no and maybe. Once a user selects one or multiple options this gets submitted to api.

I have added a default values from my receiving prop, so if a user has already got a membership it has them highlighted.

const selected = [
  {
    personId: "0001657",
    fullName: "Joe Bloggs",
    seniorStatus: "Yes",
    defaultStatus: [
      { membership: "Seniors", defaultvalue: "Yes" },
      { membership: "Juniors", defaultvalue: "No" }
    ]
  }
];

As you can see the defaultStatus field(above) has been added for the users current memberships. All this needs to do is highlight the relevant toggle, the data if not changed does not need submission to api.(below) - I would guess that the value needs to be interrogated but the value is already being used in my case.

            <ToggleButtonGroup
                className={classes.toggleButtonGroup}
                value={value[rowIdx][cellIdx.value]}
                exclusive
                onChange={(event, val) =>
                  this.handleValue(event, val, rowIdx, cellIdx.value)
                }
              >
                <ToggleButton
                  className={`w-100 ${classes.toggleButton}`}
                  value="yes"
                >
                  Yes
                </ToggleButton>
                <ToggleButton
                  className={`w-100 ${classes.toggleButton}`}
                  value="no"
                >
                  No
                </ToggleButton>
                <ToggleButton
                  className={`w-100 ${classes.toggleButton}`}
                  value="maybe"
                >
                  Maybe
                </ToggleButton>
              </ToggleButtonGroup>

Any help or assistance would be fantastic!

  1. You are using "yes", "no" and "maybe" in ToggleButton group, but using "Yes", "No" etc in default value. I guess that is a typo, both need to match.
  2. Now you can set the value like this:
    \nvalue={ \n  value[rowIdx]["defaultStatus"] && // check if defaultStatus exists \n  value[rowIdx]["defaultStatus"].filter( // filter the defaultStatus \n    ds => ds.membership === cellIdx.label // and look for the specific membership type \n  )[0] // check if that exists    \n    ?  value[rowIdx]["defaultStatus"].filter( \n        ds => ds.membership === cellIdx.label \n      )[0].defaultvalue // set the value \n    : null // otherwise null \n} \n

Here is your forked example: https://codesandbox.io/s/mjk9zy5rqp?fontsize=14

PS:

  • I noticed the logic of handleValue will not work anymore . Looks like it was a 2D array previously and now you have defined it according to a new schema. May be you are in the middle of an edit. But so you know.
  • I think it would be better if you make defaultStatus like this, instead of an array:
    \ndefaultStatus: { \n  Seniors: "yes", \n  Juniors: "no" \n}  

This way you won't have to filter the array like I did in the example. You could simply use value[rowIdx]["defaultStatus"][cellIdx.label] as value.

Update:

Your handleValue function is not working because you are setting the state in wrong place (probably from your old state design). You need to modify it to incorporate you new state design:

handleValue = (event, val, rowIdx, cellIdx) => {
    ...
    if (!newValue[rowIdx]["defaultStatus"]) {   // check if you have defaultStatus for that row
      newValue[rowIdx]["defaultStatus"] = [];   // create empty array if that doesn't exist
    }
    const updatable = newValue[rowIdx]["defaultStatus"].filter(  // find the column corresponding to the membership
      ds => ds.membership === cellIdx                       
    );

    if (updatable[0]) {                   // if such column exists
      updatable[0]["defaultvalue"] = val; // update the defaultvalue
    } else {
      newValue[rowIdx]["defaultStatus"].push({  // otherwise create a new defaultvalue
        membership: cellIdx,
        defaultvalue: val
      });
    }
    this.setState({
      value: newValue
    });
  };

See my updated code in the same sandbox url. Again, the logic could be much simplified with a plain object instead of an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM