Is it possible to incorporate a Material-UI theme palette color into a personalized React component?

My custom Sidebar component needs to have its background color set using Material-UI's primary palette color.

Sidebar.js

import styles from '../styles/Home.module.css';

export default function Sidebar() {
  return (
    <div className={styles.sidebar}>
      <hr className={styles.divider} />
    </div>
  )
}

Home.module.css

.sidebar {
   left: 0;
   top: 64px;
   height: 100vh;
   z-index: 20;
   width: 60px;
   position: fixed;
}

_app.js

import '../styles/globals.css';
import NavBar from '../components/NavBar';
import Sidebar from '../components/Sidebar';

function MyApp({ Component, pageProps }) {
  return (
    <>
      <NavBar></NavBar>
      <Sidebar color="primary"></Sidebar>
      <Component {...pageProps} />
    </>
  )
}

export default MyApp

The

<Sidebar color="primary">
tag is currently not functioning as expected. I am exploring solutions on how to implement this feature.

Answer №1

To access the theme values, you have two options: you can either use a HOC or utilize the useTheme hook.

https://material-ui.com/styles/advanced/#accessing-the-theme-in-a-component

Once you have retrieved the theme color, you can then pass it down to the Sidebar component.

function MyApp({ Component, pageProps }) {
  const theme = useTheme();
  return (
    <>
      <NavBar></NavBar>
      <Sidebar color={theme.palette.primary1Color}></Sidebar>
      <Component {...pageProps} />
    </>
  )
}

Answer №2

After taking nipuna's advice, I was able to make it work by utilizing useTheme().

Sidebar.js

import styles from '../styles/Home.module.css';
import { useTheme } from '@material-ui/core/styles';

export default function Sidebar() {
  const theme = useTheme();
  return (
    <div style={{ backgroundColor: theme.palette.primary.main }} className={styles.sidebar}>
      <hr className={styles.divider} />
    </div>
  )
}

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

Why is my database being accessed by my Prisma unit tests?

After following the Unit testing with Prisma guide, I wrote a unit test for a function that interacts with my database. Despite mocking the Prisma client as suggested in the guide to prevent database calls, when I run the test, data is actually created in ...

Dropdown select utilized to modify the value in MUI Datetimepicker

Currently, I am facing an issue with the react datetimepicker where the value does not change when selecting an option (for example: choosing 6 months should update the finish date to reflect this selection). Below is the code snippet: Child Component c ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...

Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here. The goal is to have the white part visible when the position is at the top, and switch to the blu ...

Configure unique headers for various environments

I am looking to customize headers like "id", "env", and "name" based on different environments in my application. Each environment has a unique set of values for these headers. I am struggling to implement this effectively within my existing code logic. T ...

What is the process for running the test suite prior to every build?

My current process involves running npm test followed by npm build. Is there a way to merge the test command into the build command so that it automatically runs every time I build? Here is my package.json configuration: "scripts": { " ...

The react application encountered an error: SyntaxError was thrown due to an unexpected token '<'

I've been spending a lot of time trying to find a solution, but unfortunately, I haven't been able to get it right. Uncaught SyntaxError: Unexpected token '<,' Manifest: Line: 1, column: 1, Syntax error. After deploying React on ...

Switch background color multiple times on click using JavaScript loop

Hello amazing people! I have a container with 52 small boxes and one large box containing a letter. The smaller boxes are arranged around the larger one using CSS grid, and when hovered over, they turn light grey. My Objective When any of the 52 small b ...

Using PHP to create multiple div elements and then concealing them all

I'm having an issue with the hide feature not working. My intention is to hide each dynamically generated div and gain control over them, but the problem seems to lie in the div id incrementing. Any assistance would be greatly appreciated! <?php $ ...

What steps should I take to ensure that my NodeJS application starts successfully within a Docker environment?

I am currently working with a NodeJS (version 8) application that I am attempting to run in Docker locally. After building the app, when using docker-compose up, I encounter the following error: app_1 | /app/backend/node_modules/.bin/node: 1: ...

Issue with Material-UI and React: Changes not visible after using <ThemeProvider>

I've encountered an issue where the "ThemeProvider" tag does not seem to be causing any changes in my project, even when following a simple example like the one shown below. Despite having no errors or warnings in the browser console (except for some ...

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 ...

What could be causing the data to not load from the database when the page is loaded?

My current setup involves a button that triggers a specific function upon loading. return ( <> <LikeButtonStyle onLoad={getUserData} onClick={addInfo}> <Image width="10px" height="auto" src="/ ...

What is the best way to modify an array of objects within component state?

I am currently working on updating a specific property of an object that is stored in an array. Here's a glimpse of my current state: state = { todos: [ { id: '1', title: 'first item, completed: false }, { ...

A guide on automatically focusing on a Material UI Formik form TextField using React and TypeScript

I'm attempting to automatically focus my textField, but the 'autoFocus' attribute only seems to work after I submit the form and add a value. If no values are added (i.e. when opening the miui modal for the first time), the autoFocus does no ...

Is it possible to reposition the vertical scrollbar to a location that is not on the left or right side?

Whenever I resize my modal on small screens, a horizontal scrollbar appears, causing the vertical scrollbar to disappear as it gets stuck on the right side. I am looking for a solution to keep the vertical scrollbar on the right side of the modal while scr ...

Inline CSS not appearing correctly upon initial page load

Is your page rendering incorrectly on the first load but then correct after a refresh? It seems to be related to the "display:inline-block" style. Despite clearing cache before loading, the issue persists and you're unable to find a solution. First L ...

Flex items are overflowing, rather than adjusting their size

Here .header { display: flex; font-family: monospace; background: papayawhip; align-items: center; justify-content: space-between; margin-left: auto; } ul { display: flex; background: papayawhip; gap: 10em; list-style-type: none; f ...

Issue: The process of gathering data for /dashboard/widget page is still experiencing timeouts despite two previous attempts in NextJS

While attempting to compile the code for Next.js, a warning is displayed: info - Compiled successfully warn - Restarted collecting page data for /dashboard/widget because it took more than 60 seconds warn - See more info here https://nextjs.org/docs/mes ...

Discovering the art of extracting Embeddable Links from Markdown and displaying them using personalized React Components

I am looking for a way to convert Twitter tags from Markdown to Html. Currently, I am utilizing react-markdown for rendering as shown below import gfm from 'remark-gfm' const content = `#Hello <br/><hr/> <p>Please check out th ...