Reputation: 1745
I'm just wondering what is the most efficient/elegant way to do this?
I have a component and it will set the color based on percent. Currently, the function is not working.
const App = () => {
const [progress, setProgress] = useState(51);
const [color, setColor] = useState("");
const updateColor = color => {
if (progress >= 35) {
setColor("#E75143");
} else if (progress < 36 && progress > 60) {
setColor("#FFBF00");
} else if (progress < 61) {
setColor("#13D1C5");
}
};
return (
<div>
<Progress
/* strokeColor={updateColor(color)} */ strokeColor={color}
percent={progress}
/>
</div>
);
};
export default App;
Upvotes: 2
Views: 343
Reputation: 53874
If we talking about a more "elegant" solution, I would suggest something like this with a colors config, as it's more "maintainable":
// This object can be used across all applications.
const COLORS = {
OPTION1: {
color: 'FFBF00',
interval: [0, 34]
},
OPTION2: {
color: '#E75143',
interval: [35, 60]
},
OPTION3: {
color: '#13D1C5',
interval: [60, 100]
}
};
const getOptionByProgress = progress => {
return Object.values(COLORS).find(({ interval }) => {
const [min, max] = interval;
return min <= progress && progress <= max;
});
};
const App = () => {
const [progress, setProgress] = useState(51);
return (
<Progress
strokeColor={getOptionByProgress(progress).color}
percent={progress}
/>
);
};
export default App;
Upvotes: 2
Reputation: 1313
Create an effect that sets the color
with progress
as dependency:
useEffect(() => {
setColor(progress >= 35 ? '#E75143' : '#13D1C5')
}, [progress])
Any time the progress
state changes the effect is fired, setting color
.
Upvotes: 0
Reputation: 4278
Don't need a state for color. Use a method to retrieve the color.
const App = () => {
const [progress, setProgress] = useState(59);
const updateColor = () => {
if (progress >= 35 && progress < 60) {
return "#E75143"
} else if (progress < 35 ) {
return "#FFBF00"
} else if (progress >= 60) {
return "#13D1C5";
}
};
return (
<div>
<Progress
/* strokeColor={updateColor(color)} */ strokeColor={updateColor()}
percent={progress}
/>
</div>
);
};
Upvotes: 1