React: Conditional Styling
Intro
This will cover a basic method to get conditional or responsive styling by referencing different CSS classes in a component based on a variable.
Sample Component With Variable CSS class
We have this little component that checks the users latitude and the date and display a different set of text, icon and now font-color depending on whether season
evaluates to summer or winter.
const seasonConfig = {
summer: {
text: "It is summer.",
emoji: "🌞",
},
winter: {
text: "It is Winter.",
emoji: "❄️",
},
};
// depending on the month and latitude determine if it is summer or winter
const getSeason = (lat, month) => {
if (month > 2 && month < 9) {
return lat > 0 ? "summer" : "winter";
} else {
return lat < 0 ? "summer" : "winter";
}
};
const SeasonDisplay = (props) => {
const season = getSeason(props.lat, new Date().getMonth());
// deconstruct seasonConfig object
const{text, emoji} = seasonConfig[season];
return (
<div className={`season-display ${season}`}>
<div> Icon: {emoji} </div>
<div> Text: {text} </div>
</div>
);
};
Note that the div in this sample has this class
className={`season-display ${season}`}
Which if you are lost on this syntax is the ES15 template literal to insert the variable into the list of classes. Then we have this in the stylesheet.
.winter {
color: blue;
}
.summer {
color: red;
}
This is incredibly powerful. We could implement toggles for dark/light mode with this method. Style things differently based on any number of variables! And because we are using React if the state of any of these variables changes at any point the component will re-render, the user will not need to manually reload the page for the changes to take effect.
GitHub Repo
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.