简体   繁体   中英

pass props to styled-components selector

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?

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);

The correct syntax is this:

const Button = styled.button`
  color: black;
  color: ${props => props.active ? 'red' : ''};
`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM