Issue
The slider goes from -10 to +10. From -10 to 0, the color should be red. From 0 to +10, the color should be green.
How can I achieve this using the <Slider />
from @material-ui/core
?
Solution
I wasn't sure if you meant the rail or the track element of the Slider
- this example styles both. Essentially, it's just a case of targeting the correct classes which are exposed to you by the Material-UI API. You can get a full list of the Slider
element's classes here.
The background of the rail can be styled with a simple linear-gradient image generated by CSS, and the track itself can be conditionally styled by passing a prop to the makeStyles
function:
import React from "react";
import Slider from "@material-ui/core/Slider";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
rail: {
background: "linear-gradient(90deg, red 50%, green 50%)"
},
track: {
background: ({ value }) => (value >= 0 ? "green" : "red")
}
});
const marks = Array.from({ length: 21 }, (_, i) => ({
value: i - 10,
label: i - 10
}));
const App = () => {
const [value, setValue] = React.useState(0);
const classes = useStyles({ value });
return (
<Slider
onChange={(e, newValue) => setValue(newValue)}
max={10}
min={-10}
value={value}
classes={classes}
marks={marks}
step={1}
/>
);
};
export default App;
Taking your comment at face-value, you can also pass the value
prop to the rail and style it conditionally. You shouldn't ever need to style the left hand side of the rail gray because it will always be covered by up the track in that situation:
rail: {
background: ({ value }) =>
`linear-gradient(90deg, red 50%, ${value < 0 ? "gray" : "green"} 50%)`
},
Otherwise, I would just get rid of the track
element altogether and push up the opacity of the rail while accounting for the two different sides via two conditionals:
rail: {
opacity: 0.7,
background: ({ value }) => {
const left = value < 0 ? "red" : "gray";
const right = value < 0 ? "gray" : "green";
return `linear-gradient(90deg, ${left} 50%, ${right} 50%)`;
}
},
track: {
display: "none",
}
Answered By - lawrence-witt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.