Pass props to styled-components


I am querying data for my react site using graphql from my CMS ( in order to produce color themed pages. I want to pass a variable or props into my styled component to change the background color based on what is sent back from the CMS.

In the below example, my graphql query will return a HEX that has been inputted by the user, this would then be applied to buttons etc to theme that page.

The colour can and will change from page to page as the user will be selecting it within the CMS.

Any help would be appreciated. Code example below:



const ContactButton = styled.button `
  background: #004655;
  color: #fff;
  font-size: 2rem;
  padding: 10px;


You could do the following.

const ContactButton = styled.button`
  background: #004655;
  color: ${props => props.color || '#fff'};
  font-size: 2rem;
  padding: 10px;

See codesandbox example here.

This would be the component code:


  const [color, setColor] = React.useState("#fff");

  React.useEffect(() => {
    fetch(URL).then(data => {
  }, []);

  return (
    <div className="App">
      <ContactButton color={color}>White</ContactButton>

Answered By – Paul Fitzgerald

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published