Yuval Levy
Yuval Levy

Reputation: 2516

styled-components with custom component not applying styles

I tried the following code to style inner elements implemented by react-id-swiper: https://kidjp85.github.io/react-id-swiper/

import Swiper from 'react-id-swiper';
import styled from 'styled-components';

    const MySwiper = ({ className, children }) => (
        <Swiper className={className} {...params}>
            {children}
        </Swiper>
    )
    
    const StyledMySwiper = styled(MySwiper)`
        .swiper-container{
            background-color: red !important;
        }
        .swiper-slide{
            background-color: red !important;
        }
        .swiper-wrapper{
            background-color: red !important;
        }
    `;

and then used it in my component:

function CustomSwiper(props) {
    return (
            <StyledMySwiper>
                <div>Slide #1</div>
                <div>Slide #2</div>
                <div>Slide #3</div>
                <div>Slide #4</div>
                <div>Slide #5</div>
            </StyledMySwiper>
    );
}

export default CustomSwiper;

But the styles are not applied. what am I doing wrong here?

Upvotes: 0

Views: 2036

Answers (1)

Sarun UK
Sarun UK

Reputation: 6756

Remove .h1 from the StyledTestComponent, custom styles will apply to the TestComponent.

const StyledTestComponent = styled(MyTestComponent)`
   {
    color: red;
    font-size: 100px;
  }
`;

If TestComponent has child like below,

function TestComponent({ className }) {
    return (
        <h1 className={className}>
          <div className='child'> test div element</div> //child
            aaaaasdfsdfsd
        </h1>
    );
}

You can use div tag or className for applying the styles,

 const StyledTestComponent = styled(MyTestComponent)`
    {
    color: red;
    font-size: 100px;
  } // This will apply to the main container

  .child {
    color: green;
    font-size: 100px;
  } // This will apply to child element
`;

Upvotes: 1

Related Questions