Home > Back-end >  Nesting components in styled-components
Nesting components in styled-components

Time:01-21

I made these components:

<UserImg imgUrl={userPhoto}>
  <DropDown>
    <div onClick={handleAuth}>Sign Out</div>
  </DropDown>
</UserImg>

const DropDown = styled.div`
  letter-spacing: 0.2em;
  position: relative;
  top: 7vh;
  left: 23vw;
  border-radius: 2px;
  text-transform: uppercase;
  transition: all 0.5s ease-in;
  border: 2px solid red;
  div {
    padding: 0.3em;
  }
`;

const UserImg = styled.a`
  background-image: url(${(props) => props.imgUrl});
  background-repeat: no-repeat;
  background-size: contain;
  background-position: 30%;
  display: inline-block;
  cursor: pointer;
  position: relative;
  height: 12vh;
  width: 5vw;
  left: 25vw;
  border: 2px solid white;
  border-radius: 50%;
  &:hover {
    ${DropDown} {
      visibility: visible;
      border: 1px solid white;
      border: transparent;
      cursor: pointer;
    }
  }
`;

The UserImg component works fine, but the DropDown component is not displayed.

I expect that DropDown component is displayed.

CodePudding user response:

Your <DropDown> component is displayed, bu probably not where you expect it: it is 23vw to the right of <UserImg>, since this is the left: 23vw; position you give it in its style: enter image description here

If you want it to be 2vw to the left, you would use left: -2vw; for example.

Because <DropDown> is a child of <UserImg>, its position is relative to that parent container.

Demo: https://codesandbox.io/s/naughty-lewin-9zi6ws?file=/src/App.js

  • Related