Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to default select mui togglebutton on dynamic data

I wanted to select the first toggle button by default

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) {
  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">
      <Typography>{d.name}</Typography>
    </ToggleButton>
  ))}
 </ToggleButtonGroup>
 );
 }

handling default selection on mui toggle button with dynamic data

SandBox code here: https://codesandbox.io/s/gallant-brattain-o0drw7?file=/src/App.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading