2
votes

I have a component that accepts a prop that runs another component. It looks like this:

const IconBase = styled.div`
  // Css Styles Go Here
`;

const Icon = props => (
  <IconBase>
    <props.name />
  </IconBase>
);

This component works as follows: <Icon name={Facebook} /> -- which is basically equivalent to the following:

<Icon><Facebook /></Icon>

The <Facebook /> component comes from react-icons.

Now, this all works as I wish. What I want to do now is run a check in Styled-Components for the name prop and then output the appropriate background color. Something like this:

${props => props.name === "Facebook" && `background-color: #3b5998`}

The problem is, I don't know how to do the conditional check in Styled-Components. Checking for Facebook won't work -- as I'm not passing a String to the name component. What then, should I check for?

3

3 Answers

0
votes

How about something like this?

const mapBackgroundStyle = {
    'facebook': 'background-color: #3b5998'
};

const Button = styled.button`
  background: ${props => mapBackgroundStyle[props.name]};
`;

you could also used a function instead of an object mapping.

0
votes

Okay, so I figured it out. This is the check that works:

${props => props.name === Facebook ...

Here is why that works...

When I have the following component: <Icon name={Facebook} />, the prop value {Facebook} is a function with the name of Facebook. So that is what I need to check for, a function with a particular function name. So, all I have to do is leave off the quotes and it works.

0
votes

You can use ternary condition in styled-components this way:

const Button = styled.button background: ${props => props.name === 'Facebook' ? '#3b5998' : 'white'}; ;