Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

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;
}

summer theme

winter theme

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

Ncoughlin: Seasons

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart