iTwin / iTwinUI-react

A react component library for iTwinUI.
https://github.com/iTwin/iTwinUI
Other
83 stars 23 forks source link

fix(useTheme): Exit early if theme is set on body #963

Closed mayank99 closed 1 year ago

mayank99 commented 1 year ago

Fixes #944

Our current recommendation is to use <ThemeProvider as='body'> which sounds nice in theory, but hydrating a react component rendered as a <body> seems to be a bit difficult in practice. Next doesn't properly set context. Astro renders a duplicate a <body> element, which can be worked around by not hydrating it, but then again context will not be set.

When context is not set, this line will return undefined: https://github.com/iTwin/iTwinUI-react/blob/1b4e5c51ec6c29e8d2c4b28e6f54ebfba26e3b52/packages/iTwinUI-react/src/core/utils/hooks/useTheme.ts#L55

So instead of relying entirely on context check, I'm now explicitly checking if <body> has data-iui-theme set, and exiting from the useEffect if it does. This avoids running the code which erroneously adds the theme on <html> (mentioned in #944).

As a bonus, this approach will also allow users to bypass using our ThemeProvider and manually set the data attributes in whatever they prefer.