Day 20-21: Master karo React mein styling ke saare tarike!
Dekho dosto, React mein styling karna matlab hai apne components ko sundar aur attractive banana. Jaise hum apne ghar ko decorate karte hain, waise hi React components ko bhi style karna padta hai. Lekin React mein styling ke bahut saare tarike hain - traditional CSS se lekar modern styled-components tak!
Global CSS, CSS Modules, Styled Components, aur bahut kuch!
Optimized styling for faster load times
Choose karo jo tumhare project ke liye best hai
Mobile se desktop tak perfect display
Ye sabse purana aur simple tarika hai! Isme hum normal CSS file banate hain aur use import kar lete hain. Jaise traditional websites mein karte the, waise hi. Lekin iska ek problem hai - saare styles global ho jate hain, matlab kisi bhi component mein apply ho sakte hain.
/* styles.css */
.button {
background-color: #61dafb;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: #4fa8c5;
}
/* App.js */
import './styles.css';
function App() {
return <button className="button">Click Me</button>;
}
Ye box global CSS se styled hai!
CSS Modules ek game-changer hai! Isme har component ki apni CSS file hoti hai aur wo automatically scoped ho jati hai. Matlab ek component ki styling dusre component ko affect nahi karegi. Ye Create React App mein by default supported hai!
/* Button.module.css */
.button {
background-color: #e1bee7;
color: #4a148c;
padding: 12px 24px;
border: 2px solid #9c27b0;
border-radius: 8px;
font-weight: bold;
}
.button:hover {
background-color: #ce93d8;
transform: scale(1.05);
}
/* Button.js */
import styles from './Button.module.css';
function Button() {
return <button className={styles.button}>Click Me</button>;
}
/* Multiple classes */
<div className={`${styles.card} ${styles.active}`}>Content</div>
Ye box CSS Modules se styled hai - completely scoped!
Ye sabse popular CSS-in-JS library hai! Isme tum JavaScript ke andar hi CSS likh sakte ho. Bahut powerful hai kyunki tum props ke basis pe dynamic styling kar sakte ho. Tagged template literals ka use karte hain isme.
npm install styled-components
import styled from 'styled-components';
vscode-styled-components - syntax highlighting ke liye
import styled from 'styled-components';
// Basic styled component
const Button = styled.button`
background-color: ${props => props.primary ? '#61dafb' : '#gray'};
color: white;
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease;
&:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`;
// Extending styles
const PrimaryButton = styled(Button)`
background-color: #61dafb;
font-weight: bold;
`;
// Using with props
function App() {
return (
<>
<Button primary>Primary Button</Button>
<Button>Secondary Button</Button>
<PrimaryButton>Extended Button</PrimaryButton>
</>
);
}
// Theming support
import { ThemeProvider } from 'styled-components';
const theme = {
colors: {
primary: '#61dafb',
secondary: '#282c34',
}
};
const ThemedButton = styled.button`
background: ${props => props.theme.colors.primary};
`;
function App() {
return (
<ThemeProvider theme={theme}>
<ThemedButton>Themed Button</ThemedButton>
</ThemeProvider>
);
}
Dynamic styling with props!
Emotion bhi ek powerful CSS-in-JS library hai! Ye styled-components jaisi hai lekin thodi zyada flexible aur performant. Isme do tarike hain styling karne ke - styled API aur css prop. Bahut fast hai aur bundle size bhi chota hai!
npm install @emotion/react @emotion/styled
/** @jsxImportSource @emotion/react */
{
"compilerOptions": {
"jsxImportSource": "@emotion/react"
}
}
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import styled from '@emotion/styled';
// Method 1: css prop
const buttonStyle = css`
background-color: #b2dfdb;
color: #004d40;
padding: 12px 24px;
border: 2px solid #00796b;
border-radius: 8px;
cursor: pointer;
&:hover {
background-color: #80cbc4;
}
`;
function App() {
return <button css={buttonStyle}>Click Me</button>;
}
// Method 2: styled API
const Button = styled.button`
background-color: #b2dfdb;
color: #004d40;
padding: 12px 24px;
border: 2px solid #00796b;
border-radius: 8px;
`;
// Method 3: Object styles
const objectStyle = css({
backgroundColor: '#b2dfdb',
color: '#004d40',
padding: '12px 24px',
'&:hover': {
backgroundColor: '#80cbc4'
}
});
// Composition
const baseButton = css`
padding: 12px 24px;
border-radius: 8px;
`;
const primaryButton = css`
${baseButton}
background-color: #61dafb;
color: white;
`;
Tailwind CSS ek revolutionary approach hai! Isme pre-defined utility classes hote hain jo tum directly HTML mein use karte ho. Custom CSS likhne ki zarurat nahi padti. Bahut fast development hoti hai isse aur consistent design bhi milta hai!
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {
colors: {
primary: '#61dafb',
}
},
},
plugins: [],
}
/* index.css */ @tailwind base; @tailwind components; @tailwind utilities;
// Basic usage
function Button() {
return (
<button className="bg-blue-500 hover:bg-blue-700 text-white
font-bold py-2 px-4 rounded
transition duration-300 ease-in-out
transform hover:scale-105">
Click Me
</button>
);
}
// Responsive design
function Card() {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="bg-white p-6 rounded-lg shadow-md">
Card 1
</div>
</div>
);
}
// Dark mode support
function DarkModeExample() {
return (
<div className="bg-white dark:bg-gray-800
text-black dark:text-white">
Content
</div>
);
}
// Custom classes with @apply
/* styles.css */
@layer components {
.btn-primary {
@apply bg-blue-500 hover:bg-blue-700 text-white
font-bold py-2 px-4 rounded;
}
}
Utility classes se styled!
Agar tum jaldi kaam karna chahte ho, to UI libraries best hain! Material UI, Chakra UI, Ant Design - ye sab pre-built components dete hain jo already styled hote hain. Tum bas import karo aur use karo. Customization bhi kar sakte ho!
npm install @mui/material @emotion/react @emotion/styled
npm install @mui/icons-material
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
// Material UI Example
import { Button, TextField, Card, CardContent } from '@mui/material';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import DeleteIcon from '@mui/icons-material/Delete';
const theme = createTheme({
palette: {
primary: {
main: '#61dafb',
},
secondary: {
main: '#ff6b6b',
}
},
});
function App() {
return (
<ThemeProvider theme={theme}>
<Card>
<CardContent>
<TextField
label="Name"
variant="outlined"
fullWidth
margin="normal"
/>
<Button
variant="contained"
color="primary"
startIcon={<DeleteIcon />}
>
Submit
</Button>
</CardContent>
</Card>
</ThemeProvider>
);
}
npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion
import { ChakraProvider } from '@chakra-ui/react';
function App() {
return (
<ChakraProvider>
{/* Your app */}
</ChakraProvider>
);
}
// Chakra UI Example
import { Button, Input, Box, Stack, useColorMode } from '@chakra-ui/react';
function App() {
const { colorMode, toggleColorMode } = useColorMode();
return (
<Box p={8} bg={colorMode === 'light' ? 'white' : 'gray.800'}>
<Stack spacing={4}>
<Input placeholder="Enter name" size="lg" />
<Button colorScheme="blue" size="lg">
Submit
</Button>
<Button onClick={toggleColorMode}>
Toggle {colorMode === 'light' ? 'Dark' : 'Light'}
</Button>
</Stack>
</Box>
);
}
npm install antd
import 'antd/dist/reset.css';
// Ant Design Example
import { Button, Input, Card, Space } from 'antd';
import { DeleteOutlined, SearchOutlined } from '@ant-design/icons';
function App() {
return (
<Card title="User Form" style={{ width: 400 }}>
<Space direction="vertical" style={{ width: '100%' }}>
<Input
placeholder="Enter name"
prefix={<SearchOutlined />}
size="large"
/>
<Button
type="primary"
icon={<DeleteOutlined />}
size="large"
block
>
Submit
</Button>
</Space>
</Card>
);
}
Google's Material Design
Simple & Modular
Enterprise-grade
Aaj kal har device pe website chalti hai! Mobile, tablet, laptop, desktop - sabke liye responsive design banana bahut zaroori hai. Media queries, flexbox, aur grid ka use karke hum responsive layouts bana sakte hain.
// CSS Media Queries
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
}
@media (max-width: 1024px) {
.container {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
}
// Tailwind Responsive Classes
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div>Item 1</div>
<div>Item 2</div>
</div>
Window resize karo aur dekho kaise layout change hota hai!
Dark mode ab har app mein hona chahiye! Users ko choice deni chahiye ki wo light ya dark theme use karein. CSS variables, context API, ya localStorage ka use karke implement kar sakte hain.
// Method 1: CSS Variables Approach
:root {
--bg-color: #ffffff;
--text-color: #333333;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
// React Implementation
function App() {
const [theme, setTheme] = useState('light');
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
}, [theme]);
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<button onClick={toggleTheme}>
Toggle {theme === 'light' ? '🌙' : '☀️'}
</button>
);
}
// Method 2: Styled Components
import { ThemeProvider } from 'styled-components';
const lightTheme = {
bg: '#ffffff',
text: '#333333',
};
const darkTheme = {
bg: '#1a1a1a',
text: '#e0e0e0',
};
function App() {
const [isDark, setIsDark] = useState(false);
return (
<ThemeProvider theme={isDark ? darkTheme : lightTheme}>
{/* Your app */}
</ThemeProvider>
);
}
// Method 3: Chakra UI
import { useColorMode } from '@chakra-ui/react';
function App() {
const { colorMode, toggleColorMode } = useColorMode();
return (
<Button onClick={toggleColorMode}>
Toggle {colorMode === 'light' ? 'Dark' : 'Light'}
</Button>
);
}
// Method 4: Tailwind CSS
// Enable dark mode in tailwind.config.js
module.exports = {
darkMode: 'class', // or 'media'
// ...
}
// Use dark: prefix
<div className="bg-white dark:bg-gray-800 text-black dark:text-white">
Content
</div>
Upar right corner mein button se dark mode toggle karo!
Current theme automatically changes karta hai!
Yahan kuch important tips hain jo tumhe production-ready apps banane mein help karengi:
BEM methodology ya consistent naming convention follow karo
Common styles ko variables ya mixins mein store karo
Unused CSS remove karo, critical CSS inline karo
Color contrast, focus states, aur ARIA labels use karo
Styles ko components ke saath co-locate karo
Colors, spacing, typography ko standardize karo
// Design Tokens Example
const theme = {
colors: {
primary: '#61dafb',
secondary: '#282c34',
success: '#4caf50',
error: '#f44336',
},
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px',
},
typography: {
fontFamily: "'Segoe UI', sans-serif",
fontSize: {
sm: '12px',
md: '16px',
lg: '20px',
xl: '24px',
},
},
};
Yahan 7 important interview questions hain jo tumse puchhe ja sakte hain. Click karke answers dekho!
Answer:
Regular CSS: Global scope mein hota hai, saare classes globally available hote hain, naming conflicts ho sakte hain.
CSS Modules: Local scope mein hota hai, har component ki apni scoped classes hoti hain, automatically unique class names generate hote hain.
// Regular CSS
import './styles.css';
<div className="button">Click</div>
// CSS Modules
import styles from './Button.module.css';
<div className={styles.button}>Click</div>
Key Point: CSS Modules prevent naming collisions and provide component-level encapsulation.
Answer:
CSS-in-JS: JavaScript ke andar CSS likhne ka approach hai. Libraries like styled-components aur Emotion iska use karti hain.
Advantages:
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px 20px;
`;
Answer:
Dark mode implement karne ke multiple approaches hain:
1. CSS Variables Approach:
// Define CSS variables
:root {
--bg-color: #fff;
--text-color: #333;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
}
// React component
function App() {
const [theme, setTheme] = useState('light');
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
}, [theme]);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
);
}
2. Context API Approach: Global theme state manage karne ke liye
3. Styled Components ThemeProvider: Theme object pass karne ke liye
Answer:
Performance Comparison:
Optimization Tips:
Answer:
Styled-Components:
Emotion:
// Styled-Components
import styled from 'styled-components';
const Button = styled.button`
color: blue;
`;
// Emotion - styled API
import styled from '@emotion/styled';
const Button = styled.button`
color: blue;
`;
// Emotion - css prop
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
<button css={css`color: blue;`}>Click</button>
Answer:
Multiple Approaches:
1. CSS Media Queries:
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
}
2. Tailwind Responsive Classes:
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4">
Content
</div>
3. JavaScript Window Resize:
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
useEffect(() => {
const handleResize = () => {
setIsMobile(window.innerWidth < 768);
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
4. React Responsive Library: useMediaQuery hook use karo
Answer:
Key Factors to Consider:
Decision Matrix:
Toh dosto, humne kya seekha?
Global CSS, CSS Modules, Styled Components, Emotion, Tailwind - har ek ka apna use case hai
Right approach choose karo project requirements ke according
Media queries aur flexible layouts se har device pe perfect display
Dark mode, theming, aur dynamic styling implement karna seekha
Remember: Koi ek "best" approach nahi hai - project requirements, team experience, aur performance needs ke basis pe decision lo. Practice karo aur experiment karo different approaches ke saath!