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
CodePudding user response:
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>
);
}
CodePudding user response:
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>
);
}