Search code examples
javascriptcssreactjsstyled-components

How to use StyledComponents theme inside of Component


Below I've created a style called Link. However the theme is inside of this.props. What is the way to get the theme out of props and passed into the Link styled component?

ReferenceError: theme is not defined

import React from 'react';
import styled from 'styled-components';
import { withTheme } from 'styled-components';

export const Link = styled.p`
  position: absolute;
  z-index: 10;
  bottom: 20px;
  right: 300px;
  width: 100%;
  font-size: 1.5rem;
  text-align: right;
  cursor: pointer;

  a {
    color: ${theme.apricot};  // <-- error
    cursor: pointer;

    :hover {
      color: ${theme.offWhite};   // <-- error
    }
  }
`;

class NomicsLink extends React.Component {
  render() {
    console.log(this.props.theme);
    return (<Link>Powered by <a href="https://nomics.com/" target="blank">Nomics APIs.</a></Link>)
  }
}

export default withTheme(NomicsLink);

This console.log prints the following:

{ red: '#FF0000',
  black: '#393939',
  grey: '#3A3A3A',
  lightgrey: '#E1E1E1',
  offWhite: '#EDEDED',
  apricot: '#FEBE7E',
  margin: 0,
  padding: 0 }

Solution

  • All styled-components receive theme prop automatically.

    You can access them inside the styled component with:

    const Link = styled.a`
      color: ${props=>props.theme.apricot};
    `;
    

    More options on theming, see docs