Handling Dynamic and Conditional Styles in React JS

In React applications, handling dynamic and conditional styles is essential for building interactive and responsive user interfaces. React's declarative approach to UI components allows for easy integration of dynamic and conditional styling. By manipulating styles based on state, props, or events, developers can create highly dynamic, responsive, and customizable user experiences. In this article, we will explore different ways to handle dynamic and conditional styles in React.

1. Using Inline Styles in React

React allows you to define styles directly within the JSX code using the style attribute. This can be useful for applying dynamic styles based on component state or props.

Example 1: Changing Style Based on Component State

        
          import React, { useState } from 'react';

          const DynamicStyleButton = () => {
            const [isActive, setIsActive] = useState(false);

            const buttonStyle = {
              backgroundColor: isActive ? 'green' : 'gray',
              color: 'white',
              padding: '10px 20px',
              borderRadius: '5px',
              cursor: 'pointer'
            };

            return (
              
            );
          };

          export default DynamicStyleButton;
        
      

In this example, the button’s background color changes dynamically based on the isActive state. When the button is clicked, the background color toggles between green and gray.

2. Conditional Class Names in React

Instead of using inline styles, you can apply conditional class names to your components. This approach allows you to leverage external CSS or utility frameworks like Tailwind CSS, which provides a cleaner solution for styling.

Example 2: Conditional Class Names Based on State

        
          import React, { useState } from 'react';

          const ButtonWithConditionalClass = () => {
            const [isActive, setIsActive] = useState(false);

            return (
              
            );
          };

          export default ButtonWithConditionalClass;
        
      

In this example, the button’s class name changes conditionally based on the isActive state. When the button is clicked, it switches between bg-blue-500 (blue) and bg-gray-500 (gray) classes, which change the background color.

3. Using Template Literals for Dynamic Class Names

Template literals can be used to conditionally join multiple class names in JSX, which provides an elegant way to handle dynamic styles in React components.

Example 3: Template Literals for Dynamic Styles

        
          import React, { useState } from 'react';

          const TemplateLiteralButton = () => {
            const [isActive, setIsActive] = useState(false);

            return (
              
            );
          };

          export default TemplateLiteralButton;
        
      

In this example, the button’s background and text colors are conditionally set based on the isActive state. The bg-green-500 and bg-red-500 classes are applied depending on whether the button is active, and similarly, the text color changes using text-white and text-black.

4. Using the clsx or classnames Library

For more complex conditional class name management, the clsx or classnames library can be used. These libraries help manage conditional class names in a clean and readable way.

Example 4: Using clsx for Conditional Class Names

        
          import React, { useState } from 'react';
          import clsx from 'clsx';

          const ClsxButton = () => {
            const [isActive, setIsActive] = useState(false);

            return (
              
            );
          };

          export default ClsxButton;
        
      

In this example, the clsx library is used to conditionally apply the bg-blue-500 or bg-gray-500 classes, and the text color is also dynamically adjusted. The clsx library makes it easy to apply multiple conditions in a single className.

5. Handling Conditional Styles Based on Props

Conditional styles can also be applied based on component props. This can be helpful when styling components differently depending on the data passed to them.

Example 5: Conditional Styles Based on Props

        
          import React from 'react';

          const Alert = ({ type }) => {
            const alertStyles = {
              success: 'bg-green-500 text-white',
              error: 'bg-red-500 text-white',
              warning: 'bg-yellow-500 text-black'
            };

            return (
              
This is a {type} alert!
); }; export default Alert;

In this example, the Alert component accepts a type prop, and based on the value of the prop, it applies different background and text colors using a simple mapping. If the type is 'success', 'error', or 'warning', the corresponding styles are applied. If no type is provided, a default style is used.

6. Using Styled Components or Emotion for Dynamic Styles

For more complex and reusable styles, CSS-in-JS libraries like Styled Components or Emotion allow for conditional and dynamic styles based on props and state, offering a more componentized approach.

Example 6: Conditional Styles with Styled Components

        
          import React, { useState } from 'react';
          import styled from 'styled-components';

          const Button = styled.button`
            background-color: ${props => props.active ? 'blue' : 'gray'};
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
          `;

          const App = () => {
            const [isActive, setIsActive] = useState(false);

            return (
              
            );
          };

          export default App;
        
      

In this example, the background color of the Button component is dynamically changed based on the active prop. When the button is clicked, the background color toggles between blue and gray.





Advertisement