Reputation: 5283
I have a component Box
that looks like this:
const Box = ({ className, country }) => {
const status = myStatusFunction(country);
return (
<div className={className} status={status}>
{country}
</div>
);
};
I want to use this component in my view, but also add custom styling to it based on the status
prop, so my styled.js
looks like this:
import _Box from 'components/Box';
const Box = styled(_Box)`
${({ status }) => {
if (status === 'available') {
return css`
background-color: green;
`;
}
return css`
background-color: red;
`;
}}
`
The issue here is that the status
is undefined
here, so my question is – can you somehow access the status
prop?
Upvotes: 2
Views: 644
Reputation: 74
import { Wrapper } from './styles.js';
const Box = ({ className, country }) => {
const status = myStatusFunction(country);
return (
<Wrapper className={className} status={status}>
{country}
</Wrapper>
);
};
styles.js:
export const Wrapper = styled.div`
${({ status }) => {
if (status === 'available') {
return css`
background-color: green;
`;
}
return css`
background-color: red;
`;
}}
`
Upvotes: 1
Reputation: 216
Since React has a top-down data flow this is not possible.
I would suggest to make the status
variable a prop of the Box
component to follow the top-down data flow.
The meaning of top-down flow is that information only flows from parent to child. By encapsulating the _Box
component in the styled
function, you basically make the _Box
a child component of the newly created styled Box
. This means that you in this situation you are trying to gather information of the child in the parent component.
I hope this answers your question :)
Upvotes: 1