Cannot access state.theme in styled components

I am facing the problem of not being able to access the main theme object from my styled components. Here is example, in my src/index.js I have theme object as bellow:

const marsTheme = {
  name: "@frontity/mars-theme",
  roots: {
    /**
     * In Frontity, any package can add React components to the site.
     * We use roots for that, scoped to the `theme` namespace.
     */
    theme: Theme,
  },
  state: {
    /**
     * State is where the packages store their default settings and other
     * relevant state. It is scoped to the `theme` namespace.
     */

    theme: {
      colors: {
        primary: "pink",
        secondary: "orange",
      }, 
...

Now, when I try to these theme.colors for example in my footer.js file like this:

const FooterContainer = styled.div`
  color: ${(props) => {
    console.log({ props }); // prints out { children: { some data.. }, theme: {} }
    return "red";
  }}

As you can see, the props here doesn’t provide theme object.

I tried adding some kind of theme provider with both styled-components and @emotion/react inside of my components/index.js (Theme component) like this:

<ThemeProvider theme={{ someField: "ciao" }}>
   ....
  <Footer />
</ThemeProvider>

The result of the output is the same.

How can I link my theme properties to all of my components / styled-components?

Hi @mh123

When you use the <FooterContainer> component you should add one or more props, something like:

<FooterContainer fontcolor="{state.theme.colors.primary}" bg="{state.theme.colors.secondary}">
  ...
</FooterContainer>

Then in the styled div you would access it like this:

const FooterContainer = styled.div`
  color: ${(props) => props.fontcolor};
  background-color: ${(props) => props.bg};
`

See the @frontity/twentytwenty-theme for an example. The colours are defined in index.js and an example where they’re being used is in header.js.

Hope this helps.

1 Like

Thank you for replying.

I see, but that’s how you pass a basic prop into your Styled Component. However, I want theme object to be available on all Styled Components.

In my theme config, I have for example breakpoints, colors, fonts, etc. Why would I for example pass down manually theme.breakpoints prop to every single component? I need this to be available on all components.

As I can remember, when you define a theme in styled-component and wrap the app with the <ThemeProvider theme={myTheme}> ... </Theme> the theme prop will be available in all elements wrapped by the ThemeProvider.

I am looking forward to achieving this in Frontity app as well.