Search code examples
reactjsgatsbystyled-components

Having trouble referring to another component within a component


I'm trying to change the float on a div based on the order it shows up on the page – e.g. odd float left, even float right – but nothing is happening when I refer to the component within an existing component.

This is built in reactjs using gatsbyjs and styles-components.

I can get the &:nth-of-type(even) to work if I do something like:

${Image}:before {
    background: red;
}

But without ':before' nothing happens. At least nothing that I can tell.

More specifically – and perhaps there's a better way to do this – what I'm trying to do is for even articles in the BlogList, the Image floats right. The odd articles float left. I've simplified my code since y'all don't need to see background colors etc.

const Wrapper = style.article`
    &:nth-of-type(even) {
        ${Image} {
            float: right;
        }
    }
`;

const Image = style.div`
    float: left;
`;

const Info = style.div`
    float: right;
`;

const BlogList = ({ title, cover, excerpt }) => (
    <Wrapper>
        <Image>
            <Img fluid={cover} />
        </Image>
        <Info>
            <h2>{title}</h2>
            <p>{excerpt}</p>
        </Info>
    </Wrapper>
);

In theory, by the way I read this, I should get the in event to float left. But I'm not. What am I missing here?


Solution

  • I've figured this out. Turns out I was referring to the components backwards. While I am sure there is a cleaner answer, the following is what worked for me:

    const Wrapper = styled.article`
    `;
    
    const Image = styled.div`
        ${Wrapper}:nth-of-type(odd) & {
            float: left;
        }
        ${Wrapper}:nth-of-type(even) & {
            float: right;
        }
    `;
    
    const Info = styled.div`
        ${Wrapper}:nth-of-type(odd) & {
            float: right;
        }
        ${Wrapper}:nth-of-type(even) & {
            float: left;
        }
    `;