Open In App

How to Conditionally Set Background Color in React Component with Tailwind CSS?

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In React, you might often need to change the background color of a component based on certain conditions, like highlighting a box if a value is "true" or changing it based on user input. With Tailwind CSS, you can handle this easily using its utility classes, which allow you to conditionally apply styles without needing complex logic. In this article, we'll walk through different ways to achieve this in a React component—whether it's through simple class bindings, conditional rendering, or using Tailwind's responsive and dark mode features. It's all about making your components adapt to different situations, without cluttering your code.

Below are different approaches to conditionally apply styles in React using Tailwind CSS:

Steps to Create a React App

Step 1: Create a New React App

First, we need to install a new React app using the following command in the terminal:

npx create-react-app my-app

Step 2: Navigate in our app directory

cd my-app

Step 3: Install Tailwind CSS

Now, we install Tailwind CSS and its necessary dependencies. We run the following commands:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

The npx tailwindcss init -p command will automatically generate a tailwind.config.js file and a postcss.config.js file in our project. This setup is important for integrating Tailwind CSS into our React project.

Step 4: Configure Tailwind CSS

In the tailwind.config.js file, we need to specify the paths to all of your template files so that Tailwind can tree-shake unused styles in production. Here's the correct configuration:

// tailwind.config.js
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
// Specify the paths to all of your template files
],
theme: {
extend: {},
// Extend the default theme if necessary
},
plugins: [],
// Add any plugins if needed
};

Step 5: Include Tailwind in Your CSS

Next, include Tailwind's directives in your src/index.css (or src/App.css if we are using that instead):

/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Step 6: Start Our React App

npm start

Project Structure:

proj-stru

Updated Dependencies:

dependencies: {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

We should ensure that src/index.js file is set up correctly to render the App component:

JavaScript
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM
    .createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

Using Ternary Operators

A ternary operator is a faster way to choose between two values based on a condition. It is perfect for applying Tailwind CSS classes conditionally. First, we will create a simple React component.Then we will use a div element and conditionally apply a background color based on a isActive state.

Example: When we render this component, we will see a box with either a red or green background. Clicking the button toggles the background color.

JavaScript
// src/App.js
import React, { useState } from 'react';

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

    return (
        <div
            className={`p-4
             ${isActive ? 'bg-green-500' : 'bg-red-500'}`}>
            <p className="text-white">The
                background color is
                {isActive ? 'green' : 'red'}</p>
            <button onClick={() => setIsActive(!isActive)}
                className="mt-2 
            px-4 py-2 bg-blue-500 text-white rounded">
                Toggle Background
            </button>
        </div>
    );
}

export default BackgroundToggle;

Output:

Using Conditional (&&) Operator

If we only want to apply a class based on a condition without needing an "else" case, you can use the conditional && operator.

Example: In this example, the background will be green if isActive is true; otherwise, it will remain unchanged.

JavaScript
// src/App.js
import React, { useState } from 'react';

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

    return (
        <div className={`p-4 ${isActive && 'bg-green-500'}`}>
            <p className="text-white">
                The background color is
                {isActive ? 'green' : 'transparent'}</p>
            <button onClick={() => setIsActive(!isActive)}
                className="mt-2 px-4 py-2 
            bg-blue-500 text-white rounded">
                Toggle Background
            </button>
        </div>
    );
}

export default BackgroundToggle;

Output:

Using a Function to Determine Classes

For more complex conditions, we can use a function to determine which classes should be applied. We will create a function that checks the value of the status state and returns the appropriate background color class. Multiple buttons are buttons to set different statuses (success, error, idle), which changes the background color accordingly.

Example: This approach allows for more complex logic to determine which classes to apply based on the component’s state.

JavaScript
// src/App.js
import React, { useState } from 'react';

const BackgroundToggle = () => {
    const [status, setStatus] = useState('idle');

    const getBackgroundClass = () => {
        if (status === 'success')
            return 'bg-green-500';
        if (status === 'error')
            return 'bg-red-500';
        return 'bg-gray-500';
    };

    return (
        <div className={`p-4 ${getBackgroundClass()}`}>
            <p className="text-white">Status: {status}</p>
            <button onClick={() => setStatus('success')}
                className="mt-2 px-4 py-2 
             bg-blue-500 text-white rounded">
                Set Success
            </button>
            <button onClick={() => setStatus('error')}
                className="mt-2 px-4 py-2 
            bg-blue-500 text-white rounded">
                Set Error
            </button>
            <button onClick={() => setStatus('idle')}
                className="mt-2 px-4 py-2 
            bg-blue-500 text-white rounded">
                Reset
            </button>
        </div>
    );
}

export default BackgroundToggle;

Output:



Next Article

Similar Reads