Styled components : smart Wrapper container

203 Views Asked by At

First of all, sorry for the ambiguous title.

I'm trying to make a spinner that has a label.

spinner with text

And my spinner component is like below.

const rotate360 = keyframes`
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
`

const Circle = styled.div`
    border: 5px solid ${({ theme }) => theme.color.grey};
    border-radius: 50%;
    border-top-color: #fff;
    width: ${({ size }) => size}px;
    height: ${({ size }) => size}px;
    animation: ${rotate360} 1s ease-in-out infinite;
`

const Label = styled.p`

`

const Wrapper = styled.div`
    // I'm not sure what to add here...
`

const Spinner = ({
    size,
    text
}) => {
    return (
        <Wrapper>
            <Label>{text}</Label>
            <Circle size={size} />
        </Wrapper>
    )
}

My question is how can I make my Wrapper components to know the width of child elements without making any Refs which is inconvenient and makes component larger.

My point is to calculate each of parent's children's width and then compare them and finally let the longest one be the parent's width.

It's like if one parent div has two children. One has a length of 100px and another has a length of 200px. Then parent's length would be 200px.

1

There are 1 best solutions below

0
On

Think of my question, I realized that I don't have to calculate the width of child elements.

Instead, I just made them center aligned by the code below.

const Wrapper = styled.div`
    display: block;
    padding: 1em;
    text-align: center;
    & > ${Circle} {
        margin: auto;
        margin-bottom: 20px;
    }
`

result

Lovely result, right ?