Attempting to style multipart components as outlined in this documentation is proving to be challenging. Despite my efforts, I keep encountering the following error:
ContextError: useStyles:
styles
is undefined. It appears that I may have forgotten to wrap the components in<StylesProvider />
UPDATE: A reproducible project has also been created:
- 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
Code
Below is a minimal reproduction example that yields the same error:
import React from 'react';
import { Box, BoxProps, createStylesContext, useMultiStyleConfig, useStyles } from "@chakra-ui/react";
export function TestContainer(props: any) {
const { size, variant, children, ...rest } = props
// 2. Consume the `useMultiStyleConfig` hook
const styles = useMultiStyleConfig('TestContainer', { size, variant })
const [StylesProvider] = createStylesContext('TestContainer');
return (
<Box __css={styles.testContainer} {...rest}>
{/* 3. Mount the computed styles on `StylesProvider` */}
<StylesProvider value={styles}>{children}</StylesProvider>
</Box>
)
}
export function TestChildren({
...props
}: BoxProps): JSX.Element {
const styles = useStyles();
return <Box __css={styles.testChildren} {...props} />
}
import { createMultiStyleConfigHelpers } from "@chakra-ui/system";
const helpers = createMultiStyleConfigHelpers(['testContainer', 'testChildren'])
export const TestContainer = helpers.defineMultiStyleConfig({
baseStyle: {
testContainer: {
border: '5px solid green',
},
testChildren: {
color: 'blue',
},
},
});
Usage and error
My styling seems to be working fine because when I only use the TestContainer
, everything works smoothly:
<main>
<TestContainer>
Foo
</TestContainer>
</main>
https://i.sstatic.net/gHxVh.png
However, when I include the TestChildren
component, I encounter the error at the useStyles()
line.
<main>
<TestContainer>
<TestChildren>Bar</TestChildren>
</TestContainer>
</main>