1

I am querying data for my react site using graphql from my CMS (prismic.io) 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:

Props

props.data.case_study_color

Component

const ContactButton = styled.button `
  background: #004655;
  color: #fff;
  font-size: 2rem;
  padding: 10px;
`;
Michael
  • 807
  • 4
  • 14
  • 25

3 Answers3

6

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:

  .....component

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

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

  return (
    <div className="App">
      <ContactButton color={color}>White</ContactButton>
    </div>
  );
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • Thanks for the reply Paul - I have updated my question with a little more info but I probably should have been more specific. I am wondering how I can define `props.color` with the color that has been retrieved from the CMS? – Michael Feb 12 '20 at 23:34
  • 1
    Great - thanks Paul. I simplified it a bit so that I wasn't having to set the state and just pulled it the color directly from another component which I'll drop into another answer incase it helps anyone. Is there any issues with me not setting the state like `React.useState`? Thanks for the help! – Michael Feb 13 '20 at 00:33
2
const ContactButton = styled.button `
  background: ${props => props.caseStudyColor};
  color: #fff;
  font-size: 2rem;
  padding: 10px;
`;




<ContactButton caseStudyColor={'#004655'} />
ramamoorthy_villi
  • 1,939
  • 1
  • 17
  • 40
  • thanks for the help @ramaoorthy_villi - the accepted answer was pretty much the same as yours so I appreciate the help. – Michael Feb 13 '20 at 00:41
0

As my solution was slightly different but based on Paul's answer it might be useful for someone else.

Button Component

const ContactButton = styled.button`
background: ${props => props.themeColor || '#004655'};`

Color Component

const themeColor = props.data.case_study_color;

Button

<ContactButton themeColor={themeColor}>Get in touch</ContactButton>

Michael
  • 807
  • 4
  • 14
  • 25