0
votes

I've got a styled-component which gets some additional styles based on a property (active).

The component looks similar to this:

import styled from 'styled-components';

const Button = styled.button`
  color: black;

  ${props => props.active ? `color: red;` : ''}
`;

Within a component test I need to select the active Button which (obviously) doesn't work doing the following:

document.querySelector(Button)

since this targets all Button components, no matter if active or not.

I read the styled-components docs and googled a lot. However I haven't been able to find a way to pass specific props to the styled-components-selector. I expected something similar to the following (which does not work)

document.querySelector(Button({ active: true }))

Is there any way to achieve this or rather how do you select a styled component which has specific props?

1
In the test are you trying to confirm that the color has been set to red? Can you share the test?Alexander Staroselsky
No, it's not about the red but an active button being rendered. So the goal is to find out if there's an active button (which can't be done by checking the computed styles of that node as it's based on a theme and may change, what shouldn't affect the test)Kai

1 Answers

0
votes

I think I've found a solution which is probably the 'right' way when using styled-components.

Instead of defining the active style via props within the button component, I've created another one which extends the button. This of course forces me to use another component for the active button instead of just setting an active property.

However it's not much additional work and super easy to test. So I've decided to go this way.

const Button = styled.button`
  color: black;
`;

const ActiveButton = styled(Button)`
  color: red;
`;

document.querySelector(ActiveButton);