Ad

Passing A Custom Class/style To A Styled-component In Gatsby (React)

- 1 answer

I've created the following styled-component for my gatsby project.

import React from "react"
import styled, { css } from 'styled-components'


const Button = styled.div`
    background-color: #4E58F5;
    width: 200px;
    padding: 20px;
    margin-right: 30px;
    margin-top: 30px;
    border-radius: 30px;
    color: #FFFFFF;
    transition: background-color 0.25s ease;

  ${props => props.primary && css`
    background-color: #FFF;
    color: red;
  `}
`;

export default props => (
    <Button>{props.buttonText}</Button>
)

I've not found the examples in the documentation to be clear or consistent enough to understand how I should be passing in the "primary" option to my components.

I'm trying to do the following, on my index.js page. The Button renders, but the primary word has no effect. What am I missing here?

<Button primary buttonText="Submit" />
Ad

Answer

The component you're exporting, does not recognize the primary property, and thus cannot pass it on to the Button element. You can fix this either by exporting the styled component itself, or by passing unrecognized props to the Button.

const Button = styled.div`
  [...]
`;

export default Button;

OR

export default ({buttonText, ...props})=>(
  <Button {...props}>{buttonText}</Button>
);
Ad
source: stackoverflow.com
Ad