3
votes

How does one style conditionally with Styled Components?

I have a basic component that accepts a prop, but it doesn't seem to work (probably something really silly):

import React from 'react';
import styled from 'styled-components';

const Header = styled.h1`
  color: ${props => (props.name === 'john' ? 'red' : 'blue')};
`;

export default ({ name }) => <Header>Hello {name}!</Header>;

Edit x9k1y2656q

4

4 Answers

2
votes

You must to pass the prop to the Header component:

export default ({ name }) => <Header name={name}>Hello {name}!</Header>;
0
votes

You are not passing the name props to the header component, should be:

<Header name={name}>Hello {name}!</Header>
0
votes
export default ({ name }) => <Header>Hello {name}!</Header>;

In this case, Header Component had't any props that you defined. In React props is just like html attributes. But in your code, Hello {name} is React children, so you get the value of props.name is undefined.

0
votes

You need to pass props. Last line of code need to be edited as export default ({ name }) => <Header {...props}>Hello {name}!</Header>;