Chakra UI: Trouble with Styling Multi-part Components - StyleProvider Missing

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:

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>

https://i.sstatic.net/tKy00.png

Answer №1

According to the Chakra UI guidelines, importing useStyles from "@chakra-ui/react" is not the solution.

Instead, the correct approach is to obtain it from createStylesContext.

  const [StylesProvider, useStyles] = createStylesContext('TestContainer');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the steps for utilizing Codemod with Next.js. Avoid selecting an invalid transform option

I recently attempted to use a codemod on my pages (specifically inside index.js). npx @next/codemod pages npx: installed 440 in 15.252s Invalid transform choice, must choose one of the following: - name-default-component - withamp-to-config - url-to-with ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Is middleware sufficient to safeguard both the API route and application?

Hey there, I have a question regarding the effectiveness of middleware in protecting an application. Let's say I have api routes and server actions to interact with my database, but only the /dashboard route makes use of these elements. Should I inclu ...

What are the steps to set up NextJS 12.2 with SWC, Jest, Eslint, and Typescript for optimal configuration?

Having trouble resolving an error with Next/Babel in Jest files while using VSCode. Any suggestions on how to fix this? I am currently working with NextJS and SWC, and I have "extends": "next" set in my .eslintrc file. Error message: Parsing error - Can ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Tips for personalizing the Material-UI sticky header to work with horizontal scrolling

Check out this example of a Material UI table with a sticky header on CodeSandox: https://codesandbox.io/s/yi98d?file=/demo.tsx I encountered an issue where the left side header cells slide behind each other when I added a stickyHeader prop to the Materia ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

Creating a Robust Next.js Build with Tailor-Made Server (Nest.js)

I'm in need of assistance with compiling/building my project using Next.js while utilizing a custom server. Currently, I have integrated Nest.js (a TypeScript Node.js Framework) as the backend and nested Next.js within it. The integration seems to be ...

adjusting the color of ion-button when hovering over the cancel button

I'm working on a button bar for my app and I want the color of the button to change based on its state (false, true). Currently, the button starts out green, turns light green when hovered over, and becomes white when clicked. Once I click it, the bu ...

Inconsistencies in spacing between shapes bordering an SVG Circle using D3.js are not consistent across platforms

After creating a SVG circle and surrounding it with rectangles, I am now attempting to draw a group of 2 rectangles. The alignment of the rectangle combo can either be center-facing or outside-facing, depending on the height of the rectangle. However, I am ...

Tips for automatically collapsing the Bootstrap 4 Sidebar on smaller devices

I am currently working on some code and have successfully hidden the sidebar using a collapse button. However, I am looking to make it collapse only for small devices, similar to how the bootstrap navbar functions. <link href="https://stackpath.boots ...

Include the attribute `placeholder="blur"` on several external pictures in Next.js

Currently, I am working on a Next.js application that displays movies and their posters from an API. My goal is to implement a blur effect on all images before they are fully loaded for better visual appeal. While searching for solutions, I came across thi ...

A guide to displaying API response data in a React JS application

As a beginner in react JS, I've encountered a persistent issue. Here is the code: import React from 'react'; class SearchForm extends React.Component { async handleSubmit(event){ event.preventDefault(); try{ const url ='/jobs/ ...

Looking to launch your Next.js app on an AWS EC2 Ubuntu server? Wondering about the configuration file needed for deployment?

Is there a way to start a Next.js project without using 'npm run start' or 'npm run dev' and access it directly through the build folder? Here is an example of my configuration file: server { listen 80; server_name localhost; lo ...

recoil struggles to manage the error thrown by an asynchronous selector

Recoil offers the ability for users to throw errors in async selectors. For more information, please refer to the documentation. Both "<ErrorBoundary>" and "useRecoilValueLoadable()" can handle errors from async selectors, but I encountered issues w ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

What is the best way to create a stylish outward curve effect for an active sidebar item using just CSS

After spending a week learning frontend designs, I attempted to replicate a design from Dribble. However, I've been struggling with recreating the active style on the sidebar due to the outward curve. If anyone could provide guidance on achieving thi ...

Error in React Router when using TypeScript

Encountering errors while trying to set up router with React and TypeScript. https://i.sstatic.net/muSZU.png I have already attempted to install npm install @types/history However, the issue persists. Your assistance would be greatly appreciated. Thank y ...

Troubleshooting Problems with Material-UI DataGrid Width

Is there a way to limit the width of the DataGrid to match the width of its rows without specifying a width for the containing div? I attempted using disableExtendRowFullWidth={true} but it only affects the row widths, not the overall width of the DataGri ...

Clicking to view all profiles expanding

An application is retrieving multiple profiles from an API. The goal is to display a profile's grades when its corresponding button is clicked. However, the current issue is that clicking any button shows all profile grades. const ProfileView = () =&g ...