0
0
NextJSframework~5 mins

Conditional styling patterns in NextJS

Choose your learning style9 modes available
Introduction

Conditional styling lets you change how things look based on some condition. It helps make your app more interactive and user-friendly.

Change button color when it is clicked or disabled.
Highlight a menu item when it is active or selected.
Show error styles on a form input when the user enters wrong data.
Make text bold or different color based on user preferences.
Hide or show parts of the page with different styles depending on screen size or user actions.
Syntax
NextJS
const className = condition ? 'class-true' : 'class-false';

// In JSX
<div className={className}>Content</div>
Use JavaScript expressions inside curly braces {} in JSX to apply styles conditionally.
You can combine multiple conditions using template literals or libraries like clsx for cleaner code.
Examples
This example changes the button background and text color based on isActive.
NextJS
const isActive = true;
const className = isActive ? 'bg-blue-500 text-white' : 'bg-gray-200 text-black';

return <button className={className}>Click me</button>;
This example adds extra styles when the button is disabled, making it look faded and unclickable.
NextJS
const isDisabled = false;

return <button className={`btn ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}`}>Submit</button>;
This example uses the clsx library to add classes based on multiple conditions cleanly.
NextJS
import clsx from 'clsx';

const isError = true;
const isFocused = false;

return <input className={clsx('input', { 'border-red-500': isError, 'border-blue-500': isFocused })} />;
Sample Program

This Next.js component shows a button that toggles between ON and OFF states. The button color changes green when ON and gray when OFF. It also uses accessible attributes and focus styles for keyboard users.

NextJS
import { useState } from 'react';

export default function ToggleButton() {
  const [isOn, setIsOn] = useState(false);

  return (
    <button
      aria-pressed={isOn}
      onClick={() => setIsOn(!isOn)}
      className={`px-4 py-2 rounded transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 ${isOn ? 'bg-green-600 text-white' : 'bg-gray-300 text-black'}`}
    >
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}
OutputSuccess
Important Notes

Always use semantic HTML and ARIA attributes like aria-pressed for buttons that toggle states.

Use transition classes or CSS to smoothly animate style changes for better user experience.

Consider accessibility: ensure color contrast is good and keyboard focus styles are visible.

Summary

Conditional styling changes how elements look based on state or conditions.

Use JavaScript expressions inside JSX to apply different classes or styles.

Combine multiple conditions cleanly with template literals or helper libraries like clsx.