chakra-ui / chakra-ui-docs

Documentation website for chakra ui
https://chakra-ui.com
MIT License
303 stars 475 forks source link

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

Closed ArthurGerbelot closed 1 year ago

ArthurGerbelot commented 1 year ago

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

Chakra UI Version

2.5.5

Browser

Chrome 112.0.5615.49

Operating System

nelsieborja commented 1 year ago

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()
  ...
}
ArthurGerbelot commented 1 year ago

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.