How can I get an element's width in px in styled-components?

Viewed 3473

Since the element can vary its width depending on the content it has, I don't know how to get its width in px.

Here is the basic, simplified, structure:

// React component 

export const Navbar = ({ month }) => (
  <NavbarStyled>
    <div>
      <span>{month}</span>  //month is what varies in width
    </div>
  </NavbarStyled>
)
// NavbarStyled.js

export const NavbarStyled = styled.nav`
  ...

  span:after{
    ...  

    animation: show 1s ease forwards;
  }

  @keyframes show{
    100%{
      transform: translateX(the_element's_width_in_px);
    }
  }
`

I've tried a lot of things with no results.

Thanks!

1 Answers

You can get the width by using the getBoundingClientRect() function, which will return an object of the element's attributes. With styled components, you will need to reference the element using the useRef hook or another referencing method in order to call getBoundingClientRect().

referencedElement.getBoundingClientRect()
// Return the width by calling referencedElement.getBoundingClientRect().width
Related