score:1

Accepted answer

try defaultvalue prop, or defining with or operator

import * as react from "react";
import { typography, togglebutton, togglebuttongroup } from "@mui/material";

export default function togglebuttons() {
  const data = [
    { name: "a", title: "hello1" },
    { name: "b", title: "hello2" },
    { name: "c", title: "hello3" }
  ];
  const [select, setselected] = react.usestate<string | null>("");

  const handletoggle = (
    event: react.mouseevent<htmlelement>,
    newselect: string | null
  ) => {
    if (newselect !== null) {
      alert(newselect);
      setselected(newselect);
    }
  };

  return (
    <togglebuttongroup
      value={select || "hello1"}
      exclusive
      onchange={handletoggle}
      defaultvalue={"hello1"}
      aria-label="text alignment"
    >
      {data.map((d, i) => (
        <togglebutton key={i} value={d.title} aria-label="left aligned">
          <typography>{d.name}</typography>
        </togglebutton>
      ))}
    </togglebuttongroup>
  );
}

score:0

you need to have an active prop in the togglebutton. and also need to add the value of the selected button in the data object.


import * as react from "react";
import { typography, togglebutton, togglebuttongroup } from "@mui/material";

export default function togglebuttons() {
  const data = [
    { name: "a", title: "hello1", active:true},
    { name: "b", title: "hello2" , active:false},
    { name: "c", title: "hello3", active:false }
  ];
  const [select, setselected] = react.usestate<string | null>("");

  const handletoggle = (
    event: react.mouseevent<htmlelement>,
    newselect: string | null
  ) => {
    if (newselect !== null) {
      setselected(newselect);
    }
  };

  return (
    <togglebuttongroup
      value={select}
      exclusive
      onchange={handletoggle}
      aria-label="text alignment"
    >
      {data.map((d, i) => (
        <togglebutton key={i} value={d.title} aria-label="left aligned" selected={d.active}>
          <typography>{d.name}</typography>
        </togglebutton>
      ))}
    </togglebuttongroup>
  );
}

Related Query

More Query from same tag