10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2)

In this follow-up post, we’ll continue exploring more ways to implement conditional rendering in both CSS and React.js. These techniques will help you build dynamic and responsive UIs with ease!

1. Conditional Rendering using CSS Variables


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

In this follow-up post, we'll continue exploring more ways to implement conditional rendering in both CSS and React.js. These techniques will help you build dynamic and responsive UIs with ease!

1. Conditional Rendering using CSS Variables

You can conditionally change styles in CSS using CSS variables and update them in your React components.

/* CSS */
:root {
  --bg-color: white;
}

.conditional-div {
  background-color: var(--bg-color);
}

.dark-mode {
  --bg-color: black;
  color: white;
}

Example (React.js):

const Example1 = ({ isDarkMode }) => {
  return (
    <div className={isDarkMode ? "dark-mode conditional-div" : "conditional-div"}>
      Conditional CSS Variables based on dark mode!
    </div>
  );
};

2. Conditional Rendering with Pseudo-Classes in CSS

You can conditionally style elements in CSS based on hover, focus, and active states using pseudo-classes.

/* CSS */
.conditional-button {
  background-color: blue;
  color: white;
}

.conditional-button:hover {
  background-color: red;
}

Example (React.js):

const Example2 = () => {
  return <button className="conditional-button">Hover to Change Color</button>;
};

3. Conditional Rendering with CSS Animations

You can conditionally apply animations to elements using class changes.

/* CSS */
@keyframes slideIn {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

.slide-in {
  animation: slideIn 1s forwards;
}

Example (React.js):

const Example3 = ({ shouldSlideIn }) => {
  return (
    <div className={shouldSlideIn ? "slide-in" : ""}>
      I slide in based on condition!
    </div>
  );
};

4. Conditional Rendering with :nth-child Selector in CSS

You can conditionally apply styles to specific children of an element using :nth-child.

/* CSS */
.parent-div > div:nth-child(odd) {
  background-color: lightblue;
}

Example (React.js):

const Example4 = () => {
  return (
    <div className="parent-div">
      <div>Item 1</div>
      <div>Item 2</div>
      <div>Item 3</div>
    </div>
  );
};

5. Conditional Rendering with React Portals

React Portals allow you to conditionally render elements outside the DOM hierarchy of the parent component

import ReactDOM from "react-dom";

const Example5 = ({ showModal }) => {
  return showModal
    ? ReactDOM.createPortal(
        <div className="modal">This is a modal!</div>,
        document.getElementById("modal-root")
      )
    : null;
};

6. Conditional Rendering with Multiple Classes in React

You can conditionally apply multiple classes to an element.

const Example6 = ({ isActive, isError }) => {
  return (
    <div className={`${isActive ? "active" : ""} ${isError ? "error" : ""}`}>
      This div has conditional classes!
    </div>
  );
};

/* CSS */
.active {
  background-color: green;
}

.error {
  border: 2px solid red;
}

7. Conditional Rendering with Media Queries in CSS

You can use media queries to conditionally render styles based on the screen size.

/* CSS */
@media (max-width: 600px) {
  .mobile-view {
    background-color: yellow;
  }
}

Example (React.js):

const Example7 = () => {
  return <div className="mobile-view">This div changes color on small screens!</div>;
};

8. Conditional Rendering with React Fragments and Loops

You can conditionally render a list of items in React using loops and fragments.

const Example8 = ({ items }) => {
  return (
    <>
      {items.length > 0 ? (
        items.map((item, index) => <p key={index}>{item}</p>)
      ) : (
        <p>No items to show</p>
      )}
    </>
  );
};

9. Conditional Rendering with Styled-Components

Using styled-components, you can conditionally apply styles within your React components.

import styled from "styled-components";

const Box = styled.div`
  background-color: ${(props) => (props.isPrimary ? "blue" : "gray")};
  padding: 10px;
  color: white;
`;

const Example9 = ({ isPrimary }) => {
  return <Box isPrimary={isPrimary}>This is a styled component</Box>;
};

10. Conditional Rendering using Lazy Loading in React

With React.lazy, you can conditionally load components only when needed, improving performance.

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

const Example10 = ({ shouldLoad }) => {
  return (
    <div>
      {shouldLoad ? (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent />
        </Suspense>
      ) : (
        <p>No component to load</p>
      )}
    </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


Print Share Comment Cite Upload Translate Updates
APA

Pratik Tamhane | Sciencx (2024-09-07T14:08:09+00:00) 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2). Retrieved from https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/

MLA
" » 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2)." Pratik Tamhane | Sciencx - Saturday September 7, 2024, https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/
HARVARD
Pratik Tamhane | Sciencx Saturday September 7, 2024 » 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2)., viewed ,<https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/>
VANCOUVER
Pratik Tamhane | Sciencx - » 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/
CHICAGO
" » 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2)." Pratik Tamhane | Sciencx - Accessed . https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/
IEEE
" » 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2)." Pratik Tamhane | Sciencx [Online]. Available: https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/. [Accessed: ]
rf:citation
» 10 More Conditional Rendering Examples in CSS and React.js 🚀 (Part 2) | Pratik Tamhane | Sciencx | https://www.scien.cx/2024/09/07/10-more-conditional-rendering-examples-in-css-and-react-js-%f0%9f%9a%80-part-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.