Loading content...
Loading content...
Styling means adding design like color size layout
What is Inline Style
Style is written directly inside JSX
javascript
function App() {
return <h1 style={{ color: "red" }}>Hello</h1>
}Use double curly braces
First for JSX second for object
Use camelCase
Example backgroundColor not background-color
javascript
function App() {
const style = {
color: "white",
backgroundColor: "blue"
}
return <h1 style={style}>Hello</h1>
}Write CSS in separate file
javascript
h1 {
color: red;
}Import CSS Use in Component
javascript
import "./style.css"
function App() {
return <h1>Hello</h1>
}Easy to use
Good for global styling
CSS Modules are CSS files that work only for one component
They prevent style conflicts
No class name conflict
Better for large projects
Clean and maintainable code
Create CSS Module : File name must be
css
Button.module.cssExample CSS
plaintext
.mybutton {
color: white;
background: blue;
}Import CSS Module and Use in Component
plaintext
import styles from "./Button.module.css"
function App() {
return <button className={styles.mybutton}>Click</button>
}Class name becomes unique automatically
No conflict with other components
javascript
.primary {
background: blue;
}
.secondary {
background: gray;
}javascriptCopy
<button className={`${styles.primary}`}>Primary</button>
<button className={`${styles.secondary}`}>Secondary</button>javascript
<button className={`${styles.mybutton} ${styles.primary}`}>
Button
</button>plaintext
:global(.title) {
color: red;
}javascript
<h1 className="title">Hello</h1>Local + Global
plaintext
:global(.title) {
color: red;
}
.text {
color: blue;
}CSS Modules work per component
File name must be module css
Import as styles
Use styles.className
No style conflict
Can use global if needed
CSS in JS means writing CSS inside JavaScript
No separate CSS file needed
Write CSS in JS file
Styles are only for that component
No class name conflict
Can use dynamic styles
javascript
npm install styled-componentsplaintext
import styled from "styled-components"
const Title = styled.h1`
color: red;
background: blue;
`
function App() {
return <Title>Hello</Title>
}styled is used to create component
CSS is written inside backticks
Looks like normal CSS
javascript
const Button = styled.button`
background: ${props => props.type === "primary" ? "blue" : "gray"};
color: white;
`javascript
<Button type="primary">Primary</Button>
<Button>Default</Button>Style changes based on props
javascript
const Button = styled.button`
padding: 10px;
`
const PrimaryButton = styled(Button)`
background: blue;
`
const SuccessButton = styled(Button)`
background: green;
`Reuse styles and add changes
Styles only work in that component
No conflict with other components
javascript
import { createGlobalStyle } from "styled-components"
const GlobalStyle = createGlobalStyle`
body {
background: black;
color: white;
}
`javascript
function App() {
return (
<>
<GlobalStyle />
<h1>Hello</h1>
</>
)
}