How to know the parent element size and change child element attributes? [Styled Components]

Asked

Viewed 45 times

-3

Good afternoon, how do I know the size of an element to change the width of another child element?

I have a Container element that wraps the Table when the table have a width greater than 1400px I want to be able to know and manipulate the father Container to change some values of it, for example: I don’t want more than the thead th be it:

  thead th {
    position: sticky;
    top: 0;
  }

and yes be:

thead th {
    position: relative;
    top: 10px;
}

container element:

const Container
 = styled.div`
  overflow: scroll;
  position: relative;
  width: 1368px;

  thead th {
    position: sticky;
    top: 0;
  }

`

container and table component:

<Container>
   <Table>
    {renders}
   </Tabled>
</Container>
  • @media (min-width: 1400px) { Container > table thead th {position:Static;} }

1 answer

1


You’ll have to use the useRef to "pick up" the element and the useEffect to catch width every time it changes.

Then just check and change the style.

Something like that:

const ref = useRef(null);
const [style, setStyle] = useState({
  position: sticky,
  top: 0
});
useEffect(() => {
  const width = ref.current ? ref.current.offsetWidth : 0;

  if (width > 1400) {
    setStyle({
      position: relative,
      top: `10px`,
    })
  }

}, [ref.current]);


<Container>
  <table ref={ref}>
    <thead>
      <th style={{...style}}>

      </th>
    </thead>
  </table>

</Container>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.