I'm working on a Next.js project that utilizes styled-components. I have an array of data that I am mapping over to render child components. My child components expect an isActive
prop which I am passing from the parent. When isActive
is passed, all the styled-components returns the active state for all children, instead of only the active component.
My parent component looks something like below. I've hardcoded the first item to be active just as a test. I've verified with a debugger that only the first item has isActive
set to true
:
{reviews.map((review, index) => (
<ReviewItem
key={review.name}
review={review}
isActive={index === 0}
/>
))}
My child component looks like this:
<ReviewItemContainer $isActive={isActive}>
...
</ReviewItemContainer>
The styled-component looks like below. The background-color
is just a test property:
export const ReviewItemContainer = styled.div<{ $isActive: boolean }>`
${$isActive => ($isActive ? 'background-color: black;' : '')}
`;
I expect that only the item set to isActive
should get the black background color. However, all my child components do, even the ones with isActive === false
.
Thanks for any help you can provide. This is my first time using styled-components in any real capacity, so I might just be missing something.
You're not calling the prop you're passing and instead you're using the full props object to do the background color condition. The current $isActive
you're using is actually this object { $isActive: true || false, }
so the condition will always be truthy and your background will always default to black, in order to actually call the $isActive prop you're passing you have to change your call in the styled component to look like this
// Destructure the props object
${({ $isActive }) => ($isActive ? 'background-color: black;' : '')}
or without destructuring
${(props) => (props.$isActive ? 'background-color: black;' : '')}