Home > database >  TailwindCSS: Using a ref to calculate width using an arbitrary value
TailwindCSS: Using a ref to calculate width using an arbitrary value

Time:03-20

I have a div that is absolute and should take the full width of the page up to the md breakpoint. The width of div from the md breakpoint upward, should also be the full width of the page minus the width of a sidebar navigation menu that's on the left.

My issue is that since I'm using an ref in an Tailwind class instead of a hardcoded value the JIT compiler isn't applying the md:w-[calc(100%-${sidebarRef.current.clientWidth}px)].

What would be the correct way to implement this?

<div
  className={`absolute top-0 right-0 w-full h-full md:w-[calc(100%-${sidebarRef.current.clientWidth}px)]`}>
    // Content
</div>

CodePudding user response:

You can compute the value outside the class decoration.

render() {
    let divWidth = this.myRef.current ? this.sideBarRef.current.clientWidth : 0;
    return (
        <div
            className={`absolute top-0 right-0 w-full h-full md:w-[calc(100%-${divWidth}px)]`}>
        </div>
    )
  }
}

CodePudding user response:

Tailwind doesn't handle dynamic classes. One solution might be to use a CSS variable in your class list and then set the value using JS. Something like:

render() {
  return (
    <style>
      :root {
        --content-width: calc({`100%-${sidebarRef.current.clientWidth}px`});
      }
    </style>

    <div >
       Content
    </div>
  )
}

Working example (in straight HTML): https://play.tailwindcss.com/xqiep4ObPt - resize by moving the partition.

  • Related