Search code examples
reactjsstyled-components

How to add style to a component with styled component react?


I'm trying to add style to a component.

It works fine with a component imported from the material-ui library, but it doesn't work when it comes to my original component(that is not used in any library).

Here is the code for style with styled-component

import styled from "styled-components";
import List from "./List";
import AcUnitIcon from "@mui/icons-material/AcUnit";

export const ListCotainer = styled(List)`  // doesn't apply style
  margin: 100px;
  color: pink;
`;

export const Container = styled.div`   // applies style
  font-family: sans-serif;
  text-align: center;
  background-color: red;
`;

export const Icon = styled(AcUnitIcon)`  // applies style
  background-color: blue;
  margin: 100px;
  padding: 20px;
  ${Container}:hover & {
    background-color: green;
  }
`;

App.js

import { ListCotainer, Container, Icon } from "./styles";

export default function App() {
  return (
    <Container>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ListCotainer />
      <Icon />
    </Container>
  );
}

List.js (regular component with no library)

import React from "react";

const List = () => {
  return (
    <div>
      <h1>Hello styled component</h1>
    </div>
  );
};

export default List;


Is there any way I can add style to the List component?


Solution

  • you need to create styled CSS same as you have created for Container in your App.js. i have update your code it should work for you.

    styles.js

    import styled from "styled-components";
    import AcUnitIcon from "@mui/icons-material/AcUnit";
    
    export const ListCotainer = styled.div`
      margin: 100px;
      width: 200px;
      color: pink;
    `;
    
    export const Container = styled.div`
      font-family: sans-serif;
      text-align: center;
      background-color: red;
    `;
    
    export const Icon = styled(AcUnitIcon)`
      background-color: blue;
      margin: 100px;
      padding: 20px;
      ${Container}:hover & {
        background-color: green;
      }
    `;
    

    List.js

    import React from "react";
    import { ListCotainer } from "./styles";
    
    const List = () => {
      return (
        <ListCotainer>
          <h1>Hello styled component</h1>
        </ListCotainer>
      );
    };
    
    export default List;
    

    App.js

    import { Container, Icon } from "./styles";
    import List from "./List";
    
    export default function App() {
      return (
        <Container>
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          <List />
          <Icon />
        </Container>
      );