10 Conditional Rendering Examples in CSS and React.js πŸš€ (Part 3)



This content originally appeared on DEV Community and was authored by Pratik Tamhane

Welcome back! In this third part of our series, we’re diving into even more creative ways to achieve conditional rendering using CSS and React.js. Let’s explore new techniques to make your UI even more dynamic!

1. Conditional Rendering with React Context

Using React Context, you can pass a global state and conditionally render elements across different components without props drilling.

import React, { useContext } from "react";
import { ThemeContext } from "./ThemeContext";

const Example1 = () => {
  const { isDarkMode } = useContext(ThemeContext);

  return (
    <div style={{ backgroundColor: isDarkMode ? "black" : "white" }}>
      The theme is {isDarkMode ? "Dark" : "Light"}!
    </div>
  );
};

2. Conditional Rendering using before and after Pseudo-Elements in CSS

You can use the ::before and ::after pseudo-elements to conditionally add content before or after an element without altering the DOM.

/* CSS */
.conditional-box::before {
  content: "Before content";
  display: block;
  color: blue;
}

.conditional-box.is-highlighted::after {
  content: "Highlighted!";
  display: block;
  color: green;
}

Example (React.js):

const Example2 = ({ isHighlighted }) => {
  return <div className={isHighlighted ? "conditional-box is-highlighted" : "conditional-box"}>Box content</div>;
};

3. Conditional Rendering using React.memo

You can conditionally optimize the rendering of a component using React.memo, which will only re-render when the props change.

const ConditionalComponent = React.memo(({ isVisible }) => {
  return isVisible ? <p>This will only re-render if `isVisible` changes</p> : null;
});

Example (React.js):

const Example3 = ({ isVisible }) => {
  return <ConditionalComponent isVisible={isVisible} />;
};


4. Conditional Rendering based on User Input

Conditionally show or hide elements in response to user input (like a checkbox).

const Example4 = () => {
  const [isChecked, setIsChecked] = React.useState(false);

  return (
    <div>
      <input type="checkbox" onChange={() => setIsChecked(!isChecked)} />
      {isChecked ? <p>Checkbox is checked!</p> : <p>Checkbox is unchecked!</p>}
    </div>
  );
};

5. Conditional Styling using CSS Grid

With CSS Grid, you can conditionally change the layout based on state, screen size, or other conditions.

/* CSS */
.grid-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.grid-layout.single-column {
  grid-template-columns: 1fr;
}

Example (React.js):

const Example5 = ({ isSingleColumn }) => {
  return (
    <div className={isSingleColumn ? "grid-layout single-column" : "grid-layout"}>
      <div>Column 1</div>
      <div>Column 2</div>
    </div>
  );
};

6. Conditional Rendering using React Suspense for Code Splitting

With React Suspense, you can conditionally render components only when needed by splitting your code.

import React, { Suspense } from "react";
const HeavyComponent = React.lazy(() => import("./HeavyComponent"));

const Example6 = ({ shouldLoad }) => {
  return (
    <div>
      {shouldLoad ? (
        <Suspense fallback={<div>Loading component...</div>}>
          <HeavyComponent />
        </Suspense>
      ) : (
        <p>No heavy component to load.</p>
      )}
    </div>
  );
};

7. Conditional Rendering using CSS Transitions

You can use CSS Transitions to conditionally apply smooth transitions between states.

/* CSS */
.conditional-div {
  transition: background-color 0.3s ease;
  background-color: white;
}

.conditional-div.active {
  background-color: yellow;
}

Example (React.js):

const Example7 = ({ isActive }) => {
  return (
    <div className={isActive ? "conditional-div active" : "conditional-div"}>
      I smoothly change background color!
    </div>
  );
};

8. Conditional Rendering based on State Array Length

Render elements conditionally based on the length of an array in your React state.

const Example8 = () => {
  const [items, setItems] = React.useState([]);

  return (
    <div>
      {items.length > 0 ? (
        items.map((item, index) => <p key={index}>{item}</p>)
      ) : (
        <p>No items available.</p>
      )}
      <button onClick={() => setItems([...items, "New Item"])}>Add Item</button>
    </div>
  );
};

9. Conditional Rendering using Keyframes in CSS

You can apply conditional rendering with keyframes animations that trigger based on class changes.

/* CSS */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.fade-in {
  animation: fadeIn 0.5s forwards;
}

Example (React.js):

const Example9 = ({ shouldFadeIn }) => {
  return (
    <div className={shouldFadeIn ? "fade-in" : ""}>
      I will fade in when the condition is met!
    </div>
  );
};

10. Conditional Rendering with CSS Flexbox

You can use Flexbox to conditionally change layouts based on state.

/* CSS */
.flex-container {
  display: flex;
}

.flex-container.column {
  flex-direction: column;
}

.flex-container.row {
  flex-direction: row;
}

Example (React.js):

const Example10 = ({ isColumnLayout }) => {
  return (
    <div className={isColumnLayout ? "flex-container column" : "flex-container row"}>
      <div>Item 1</div>
      <div>Item 2</div>
    </div>
  );
};

shop Link : https://buymeacoffee.com/pratik1110r/extras

LinkedIn : https://www.linkedin.com/in/pratik-tamhane-583023217/

Behance : https://www.behance.net/pratiktamhane


This content originally appeared on DEV Community and was authored by Pratik Tamhane