Conditional ClassName
ReactJS
Medium
6 views
Problem Description
Add className based on prop without messy string building.
Output Format
Render a React component.
Constraints
Use an array join pattern.
Official Solution
import React from 'react';
function Pill({ active, children }) {
const className = ['pill', active ? 'pill--active' : null].filter(Boolean).join(' ');
return <span className={className}>{children}</span>;
}
export default function App() {
return (
<div style={{ padding: 16 }}>
<style>{'.pill{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid #ddd;margin-right:8px}.pill--active{background:#0b5;color:#fff;border-color:#0b5}'}</style>
<Pill active={true}>Active</Pill>
<Pill active={false}>Idle</Pill>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!