← Back to React Course | Chapter 11: Styling in React | Lesson 5 of 8

Conditional Class Names बनाना

Conditional class names ऐसे हैं जैसे weather के आधार पर अलग outfit चुनना — वही wardrobe, लेकिन आप actually कौन से pieces पहनते हैं यह current conditions पर depend करता है।
Syntax
markup
<div className={condition ? "class-a" : "class-b"}>...</div>

<div className={`base ${condition ? "modifier" : ""}`}>...</div>

<div className={clsx("base", { modifier: condition })}>...</div>

एक Ternary से className बनाना

किसी class को conditionally apply करने का सबसे simple तरीका एक ternary expression है सीधे className prop के अंदर, एक boolean condition के आधार पर दो class name strings में से choose करते हुए, जैसे एक button active है या disabled।

Note: सिर्फ एक या दो conditions के लिए, एक plain ternary पूरी तरह readable है और किसी extra library की ज़रूरत नहीं।
Warning: एक className string के अंदर ternaries के अंदर nested ternaries जल्दी unreadable हो जाते हैं — वह point है जहां एक helper library के लिए reach करना चाहिए।

उदाहरण: Building a className with a Ternary

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [active, setActive] = React.useState(false);
  return <button className={active ? "btn active" : "btn"} onClick={() => setActive(!active)}>Toggle</button>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

एक Base Class को Modifiers के साथ Combine करना

एक common pattern हमेशा एक base class apply करना है (जैसे btn) plus zero या ज़्यादा modifier classes (जैसे btn-primary या btn-disabled) props के आधार पर, एक template literal से built up जो हर modifier को conditionally include करता है।

Note: यह BEM CSS naming convention (block__element--modifier) को mirror करता है, जो naturally इस pattern के साथ pair होता है।
Warning: Base class और एक conditionally-added modifier के बीच एक leading space भूल जाना उन्हें एक invalid class name string में merge कर देता है।

उदाहरण: Combining a Base Class with Modifiers

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function Button({ primary, disabled, children }) {
  const className = `btn${primary ? " btn-primary" : ""}${disabled ? " btn-disabled" : ""}`;
  return <button className={className} disabled={disabled}>{children}</button>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<Button primary>Click</Button>);
  </script>
</body>
</html>

Complex Cases के लिए एक Helper Library उपयोग करना

clsx या classnames जैसी Libraries एक object लेती हैं जहां keys class names हैं और values booleans हैं, automatically सिर्फ true ones को एक final string में join करते हुए।

यह manual string building से कहीं बेहतर scale करता है जब आपके पास कई independent conditions हों।

Note: clsx({ active: isActive, disabled: isDisabled }) clearly पढ़ता है भले ही कई conditions एक साथ हों।
Warning: यह एक छोटा npm package है — इसे install करना ज़रूरी है; यहां कोई CDN-runnable equivalent नहीं दिखाया गया क्योंकि यह एक tiny, commonly-bundled utility है।

उदाहरण: Using a Helper Library for Complex Cases

markup
// Run in your local React project (npm install required)
import clsx from 'clsx';

function Button({ active, disabled, children }) {
  return <button className={clsx('btn', { active, disabled })}>{children}</button>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. clsx या classnames जैसे helper के बजाय error-prone manual string concatenation से className strings बनाना।
  2. Multiple classes manually concatenate करते समय एक space भूल जाना, accidentally दो class names को एक invalid में merge करते हुए।
  3. एक conditional class apply करना लेकिन उसके लिए कोई matching CSS rule actually define करना भूल जाना।
चैप्टर सारांश
  • एक component का className template literals या ternaries उपयोग करके props या state के आधार पर dynamically बनाया जा सकता है।
  • clsx या classnames जैसी Libraries कई conditional classes cleanly combine करना simplify करती हैं।
  • एक common pattern है एक base class हमेशा apply होना, plus conditional modifier classes।
  • Conditional classes का कोई visible effect सिर्फ तभी है जब उनके लिए matching CSS rules actually मौजूद हों।
ब्राउज़र सपोर्ट

कोई React-version restriction नहीं — template literals और ternaries plain JavaScript हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.