Search code examples
reactjsstyled-components

import statement in React / Gatsby


I am in the process of learning React and Gatsby, and I am using styled components in my project. I downloaded the default gatsby project. My setup is the following, I created a directory called styledComponents, in there I have file called DestkopMenu.js with same styling.

import styled from "styled-components"

const StyledHeader = styled.header`
  display: flex;
  position: fixed;
  align-items: center;
  width: 100%;
  top: 0;
  z-index: 10;
  padding: 0 0.5rem;
  background: white;
`

Within the same folder I also have index.js that has the following code:

export * from "./DesktopMenu"

In my components folder I have file called DesktopNav.js where I attempt to import my styled component with the following code:

import React, { useEffect, useRef, useState } from "react"
import { Link } from "gatsby"
import { StyledHeader } from "../styledComponents"

const DesktopNav = () => {
  return (
    <StyledHeader>
      <h1>Home</h1>
    </StyledHeader>
  )
}

export default DesktopNav

This fails giving me the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of DesktopNav.

So, I guess I doing the import statement the wrong way...

When putting the styled components in the same file, it naturaully works with the following code:

import React, { useEffect, useRef, useState } from "react"
import { Link } from "gatsby"
import styled from "styled-components"
//import { StyledHeader } from "../styledComponents"

const DesktopNav = () => {
  return (
    <StyledHeader>
      <h1>Home</h1>
    </StyledHeader>
  )
}

export default DesktopNav

const StyledHeader = styled.header`
  display: flex;
  position: fixed;
  align-items: center;
  width: 100%;
  top: 0;
  z-index: 10;
  padding: 0 0.5rem;
  background: white;
`

Solution

  • It's not a problem with your import, but with your export. You did not export StyledHeader.

    This statement export * from "./DesktopMenu" will export all of the named exports from the file DesktopMenu. You did not export anything from that file, so therefore the index.js will also not export anything.

    Simply export the const so that the index.js file can find it:

    export { StyledHeader };