Search code examples
javascriptecmascript-6styled-componentsgatsby

styled-components not restyling a component


I'm having some trouble 're-styling' Components in Gatsby using styled-components

"styled-components": "^3.3.0" "gatsby-plugin-styled-components": "^2.0.11"

I"ve got gatsby-plugin-styled-components in my gatsby-config and styling works on everything bar when i put a custom Component through styled() again for example:

I have a side bar styled here

import React, { Component } from "react";
import styled from "styled-components";

class Aside extends Component {
  render() {
    return (
      <Sidebar>
        <List>
          <Item>Pintrest 1</Item>
          <Item>Pintrest 2</Item>
          <Item>Pintrest 3</Item>
        </List>
      </Sidebar>
    );
  }
}

const Sidebar = styled.div`
  position: absolute;
  width: 200px;
  left: calc(100% + 20px);

  @media (max-width: 1200px) {
    position: relative;
    width: 100%;
    left: 0;
    top: 0;
  }
`;

On one page i'd like to have the style top: 0; so I pass it through

const SideBar = styled(Aside)`
  top: 0;
`;

.

import React from 'react'
import Helmet from 'react-helmet'
import Link from 'gatsby-link'
import get from 'lodash/get'
import styled from "styled-components";

import Bio from '../components/Bio'
import Aside from '../components/Aside';

class BlogPostTemplate extends React.Component {
  render() {
    const post = this.props.data.markdownRemark
    const siteTitle = get(this.props, 'data.site.siteMetadata.title')
    const { previous, next } = this.props.pathContext

    return (
      <div>
        <Helmet title={`${post.frontmatter.title} | ${siteTitle}`} />
        <Bio />
        <Post>
          <h1>{post.frontmatter.title}</h1>
          <SideBar/>
        </Post>
      </div>
    )
  }
}

but it doesn't apply to the element

And have even tried

const aside = ({className}) => <Aside className={className}/>;

const SideBar = styled(aside)`
  top: 0;
`;

like shown

https://www.styled-components.com/docs/basics#styling-any-components

but it isn't working and is not altering the style is this a limitation with the lib gatsby-plugin-styled-components or styled-components or am i misunderstanding the purpose of styled-components


Solution

  • To do it as done in the example you have linked you will need to pass a className prop to the child like this :

    class Aside extends Component {
      render() {
        return (
          <Sidebar className={this.props.className}>
            <List>
              <Item>Pintrest 1</Item>
              <Item>Pintrest 2</Item>
              <Item>Pintrest 3</Item>
            </List>
          </Sidebar>
        );
      }
    }