chakra-ui/chakra-ui-docs

StylesProvider not found by useStyles() when using Styling multipart components

ArthurGerbelot opened this issue · 2 comments

Description

When I style a multipart components TestContainer and TestChildren (both on /src/components/TestContainer.tsx)

Children component useStyles() hook cannot found the StylesProvider and return the error:

Unhandled Runtime Error
ContextError: useStyles: styles is undefined. Seems you forgot to wrap the components in <StylesProvider />

I know my style is well applied to the Chakra Theme cause when I'm using only the <TestContainer> component I have the right style on it. The issue append when I add the <TestChildren> on it

Link to Reproduction

Github: https://github.com/ArthurGerbelot/issue-chakra-ui-styling-multipart-components

CodeSandBox: https://codesandbox.io/p/github/ArthurGerbelot/issue-chakra-ui-styling-multipart-components/main

Steps to reproduce

  • Install npm install
  • Run Nextjs npm run dev (or yarn dev)
  • Go on 127.0.0.1:3000

Chakra UI Version

2.5.5

Browser

Chrome 112.0.5615.49

Operating System

  • macOS
  • Windows
  • Linux

Followed the Component Style guide and also came across the same issue. After a bit of digging, should use useStyles from your createStylesContext:

const [StylesProvider, useStyles] = createStylesContext("ParentComp")
const ParentComp = (props) =>  {
  const styles = useMultiStyleConfig("ParentComp", props)
  return <StylesProvider value={styles}>{children}</StylesProvider>
}
const ChildComp = () => {
  const styles = useStyles()
  ...
}

Okay I tried and it's working ! Thank you !

But I looked (again) on the Chakra guide and they're importing useStyles directly from @chakra-ui/react and never talk about a second arguments returned by createStylesContext.

Hopefully they will update the documentation.