admin管理员组

文章数量:1276752

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 ponent 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;
`;

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 ponent 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;
`;
Share Improve this question edited Feb 12, 2020 at 23:26 Michael asked Feb 12, 2020 at 23:05 MichaelMichael 8175 gold badges14 silver badges25 bronze badges 1
  • See the docs: styled-ponents./docs/basics#passed-props – Tim Commented Feb 12, 2020 at 23:10
Add a ment  | 

3 Answers 3

Reset to default 7

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 ponent code:

  .....ponent

  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>
  );
const ContactButton = styled.button `
  background: ${props => props.caseStudyColor};
  color: #fff;
  font-size: 2rem;
  padding: 10px;
`;




<ContactButton caseStudyColor={'#004655'} />

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>

本文标签: javascriptPass props to styledcomponentsStack Overflow