1
votes

I recently started using Gatsby for building my websites, previously I relied just on plain html and css, so I may be missing something really basic here...

I am trying to style a custom header component that looks like this

import React from "react"
import MWidth from "./m-width"

import logo from "../resources/images/logo.png"

function Header() {
   return (
      <>
         <MWidth>
            <div>
               <img src={`${logo}`}></img>
            </div>
         </MWidth>
      </>
   )
}

export default Header

after importing it inside the layout component I tried styling it with styled-components like so

const PageHeader = styled(Header)`
   background-color: #f0f;
`

but nothing changed.

I saw this approach being used with the Link component, but maybe it's defined in another way. Am I missing something or is it just a Gatsby error?

My Layout.js file looks like this

import React from "react"
import styled from "styled-components"

import Header from "./header"
import Content from "./content"
import Footer from "./footer"

import "./common.css"

const PageHeader = styled(Header)`
   background-color: #f0f;
`

function Layout(props) {
   return (
      <>
         <PageHeader />
         <Content>{props.children}</Content>
         <Footer />
      </>
   )
}

export default Layout

Let me know if you need more information. Any help would be appreciated.

Thanks ????

Edit:

Turns out that in order for this to work you have to attach a class name to the element you want to style passing it as a prop.
So as ksav suggested I added props into the Header function declaration and className={props.className} to a wrapper div. Now it looks like this

function Header(props) {
   return (
      <div className={props.className}>
         <MWidth>
            <div>
               <img src={`${logo}`}></img>
            </div>
         </MWidth>
      </div>
   )
}

which essentially is the same thing as the one he posted below. And this solved the problem.

Thank you ????

1
Where do you want the background color? - ksav
As background of the header component, but I don't want to set the colour inside the component because it's going to change for each page. - Milo

1 Answers

2
votes

Styling any component

The styled method works perfectly on all of your own or any third-party component, as long as they attach the passed className prop to a DOM element.

function Header({className}) {
  return (
    <div className={className}>
        <MWidth>
          <div>
            <img src={`${logo}`}></img>
          </div>
        </MWidth>
    </div>
  )
}