1
votes

I'm using styled-components to style a parent and child element in a component:

function StyledDemo({
  name,
  light,
  ...props
}) {
  return (
    <Parent {...props}>
      <Child>{name}</Child>
    </Parent>
  );
}

I have a light prop which is true/false - but I'm having an issue with styling the elements based on the value of that property:

const Parent = styled.div`
  background-color: #000;
  width: 100%;

  ${props => props.light && `
    background-color: #ccc;
  `}
`;

The styling only seems to work when I remove the prop being passed into the function individually.

Parent element uses correct styling based on light prop value when:

function StyledDemo({ name, ...props })

Parent element does NOT use correct styling based on light prop value when:

function StyledDemo({ name, light, ...props })

I can get it all working by setting the prop on the Parent and Child component, but this doesn't seem like it's the best way:

return (
  <Parent {...props} light={light}>
    <Child light={light}>{name}</Child>
  </Parent>
);

Is this the correct way to apply styles to components based on props, or is there an issue with my approach?

I have a demo to tinker with if it helps: https://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz

1

1 Answers

1
votes

This is not related to styled-components but to the rest parameter.

When you do the rest operator, any property you "pick" out by name won't be contained in the ...rest variable. So when you do

const Button = ({ light, ...rest }) => ()

<Button light primary />

rest will only contain the primary property, but not light, that's now it's own variable.

If you did

const Button = ({ ...rest }) => ()

<Button light primary />

instead rest would also contain light.

So in your example, you're picking out light from ...props, so when you pass {...props} on to the parent it doesn't contain light anymore, so styled-components doesn't know it exists! Either you go with your first version, or you have to manually apply it to each component.

See MDN for more information about the rest parameter!