What is Styled Components?

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:

jsx

const Button = styled.button` background: blue; color: white; `;

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

jsx
const MyDiv = ({ className, children }) => { return <button className={className}>{children}</button>; };

📝 What it means:

  • You are creating a custom button component

  • It accepts:

    • className – automatically injected by styled-components

    • children – the button text

  • It's like saying:

    html
    <button class="some-generated-css-class">Click Me</button>

🔹 Step 2: Add Styles to That Component

jsx
const StyledButton = styled(MyDiv)` padding: 10px 20px; border: none; border-radius: 5px; color: white; background-color: ${({ primary }) => (primary ? '#007bff' : '#333')}; `;

📝 What it means:

  • You take MyDiv and "wrap" it with styled()

  • 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

jsx
function App() { return ( <div> <StyledButton primary={true}>Primary Button</StyledButton> <StyledButton primary={false}>Secondary Button</StyledButton> </div> ); }

📝 What it means:

  • You are passing props (primary={true} or false)

  • That prop controls how the button looks


🖼️ Visual Example

CodeWhat You See
<StyledButton primary={true}>🔵 Blue button
<StyledButton primary={false}>⚫ Gray button

📌 Summary

ConceptMeaning
styled(MyDiv)Style your custom component
classNameSpecial 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

Post a Comment

Previous Post Next Post