I have this sandbox. This is a switch component approach based on divs, but I would like to add a smooth transition for the states, such as in this example https://codepen.io/nikkk-me/pen/abvPjeG. I added:
after: {
transform: 'translateX(120px)',
transition: 'transform 300ms linear'
}
in the styled div, but it doesn't work. Any hint on how to solve this?
CodePudding user response:
Despite the syntax error in the added code, it seems that you would like to create this effect by animating a pseudo-element.
This can be done but will require writing a complete custom component, which kinda contradicts the purpose of using MUI.
But anyways, here is a quick draft example:
Live demo: sandbox
// demo.tsx
import * as React from "react";
import { styled } from "@mui/material/styles";
import { Box, Typography } from "@mui/material";
const Selector = styled(Box)(({ selected }) => ({
display: "flex",
justifyContent: "center",
cursor: "pointer",
color: selected ? "white" : "inherit",
borderRadius: selected ? "21px" : "unset",
padding: "3px 20px 3px 20px",
width: "50px",
zIndex: "100",
transition: "color 0.2s linear"
}));
export default function BoxSx() {
const [selected, setSelected] = React.useState("first");
function handleSelected() {
setSelected(selected === "first" ? "second" : "first");
}
return (
<Box
sx={{
display: "flex",
background: "grey",
width: "fit-content",
borderRadius: "25px",
p: "2px",
isolation: "isolate",
position: "relative",
"&::before": {
content: "''",
position: "absolute",
backgroundColor: "pink",
padding: "3px 20px 3px 20px",
width: "50px",
borderRadius: "21px",
zIndex: "50",
top: "0",
left: selected === "first" ? "0" : "93px",
bottom: "0",
transition: "left 0.2s linear"
}
}}
onClick={handleSelected}
>
<Selector selected={selected === "first"} color="green">
<Typography sx={{ fontWeight: "bold" }}>First</Typography>
</Selector>
<Selector selected={selected === "second"} color="green">
<Typography sx={{ fontWeight: "bold" }}>Second</Typography>
</Selector>
</Box>
);
}