SmartCodingTips

๐ŸŽฏ Conditional Styling in React

Conditional styling allows you to apply styles based on dynamic values like props, state, or context. This is essential for building responsive, interactive UIs.


๐Ÿงช 1. Inline Styling with Ternary


function Button({ isActive }) {
  return (
    <button
      style={{
        backgroundColor: isActive ? '#22c55e' : '#ef4444',
        color: 'white',
        padding: '10px 16px',
      }}
    >
      {isActive ? 'Active' : 'Inactive'}
    </button>
  );
}

๐ŸŽจ 2. Class-based Styling

Use ternary logic in the className attribute:


function Card({ selected }) {
  return (
    <div
      className={`p-4 rounded shadow ${
        selected ? 'bg-blue-600 text-white' : 'bg-gray-100 text-black'
      }`}
    >
      Card Content
    </div>
  );
}

๐Ÿ“ฆ 3. CSS Modules


// Card.module.css
.card {
  padding: 1rem;
  border-radius: 8px;
}
.selected {
  background-color: #0ea5e9;
  color: white;
}

import styles from './Card.module.css';

function Card({ selected }) {
  return (
    <div className={`${styles.card} ${selected ? styles.selected : ''}`}>
      CSS Modules Example
    </div>
  );
}

๐Ÿ’… 4. Styled Components


import styled from 'styled-components';

const Box = styled.div`
  background-color: ${(props) => (props.active ? '#4ade80' : '#f87171')};
  color: white;
  padding: 16px;
  border-radius: 8px;
`;

function StatusBox({ active }) {
  return <Box active={active}>Status</Box>;
}

๐Ÿ”ง 5. Using clsx / classnames

To cleanly manage conditional classes:


import clsx from 'clsx';

function Button({ primary }) {
  return (
    <button
      className={clsx('px-4 py-2 rounded', {
        'bg-blue-600 text-white': primary,
        'bg-gray-300 text-black': !primary,
      })}
    >
      Submit
    </button>
  );
}

๐Ÿ“Œ Summary

  • Use ternary operators for simple inline or class-based conditions
  • Use clsx or classnames for complex logic
  • Styled Components and Emotion support props for dynamic styling
  • CSS Modules also support scoped + conditional class merging