Styled Components is a library for styling React components using CSS inside JavaScript.
Instead of writing CSS in separate .css
files, you write styles inside your JS/JSX code, like this:
Now Button
is a React component you can use, and it will have those styles.
🧠 What's Special in Your Image?
You're looking at an advanced trick where:
-
You create a normal React component first (
MyDiv
) -
Then use
styled(MyDiv)
to style it -
Then you use interpolation to change style based on props (like
primary
)
Let me explain all 4 steps from the image in detail:
✅ Step-by-Step Explanation
🔹 Step 1: Create a Custom React Component
📝 What it means:
-
You are creating a custom button component
-
It accepts:
-
className
– automatically injected bystyled-components
-
children
– the button text
-
-
It's like saying:
🔹 Step 2: Add Styles to That Component
📝 What it means:
-
You take
MyDiv
and "wrap" it withstyled()
-
You write CSS inside backticks (
`...`
) -
primary
is a prop (like a variable) passed from the parent
✅ If primary
is true
, background = blue (#007bff
)
❌ If false
, background = gray (#333
)
🔹 Step 3: Use the Styled Button in Your App
📝 What it means:
-
You are passing props (
primary={true}
orfalse
) -
That prop controls how the button looks
🖼️ Visual Example
Code | What You See |
---|---|
<StyledButton primary={true}> | 🔵 Blue button |
<StyledButton primary={false}> | ⚫ Gray button |
📌 Summary
Concept | Meaning |
---|---|
styled(MyDiv) | Style your custom component |
className | Special prop used for styling |
primary={true} | A way to customize component behavior |
${({ primary }) => ...} | JS logic inside style (called interpolation) |
https://chatgpt.com/share/68669f61-e52c-8011-bc97-cbddbb2b09f8