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

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

Scrollable tabs with FlatLists inside a ScrollView, reminiscent of the layout found on popular social media profile

I am seeking to implement a set of tabs, each containing a FlatList within a ScrollView, similar to the layout seen on Instagram or Twitter. However, I have encountered challenges with having a FlatList within a ScrollView and triggering the onEndReached ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Guide on how to deactivate the Navbar component on specific dynamic routes in next.js

I have found one method to achieve this using the next router, specifically for static routes like /dashboard'. However, I am searching for a solution for dynamic URLs such as '/story/[slug]'. Layout.js const Layout=({children })=>{ i ...

Attempting to assign a specific font style to a dropdown selection menu

Trying to assign a font-family to the options in my select menu but facing issues. The code below seems to work on Google Chrome, but I'm getting a different font-family on Internet Explorer. Any suggestions on how to set a font-family that works on ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Display or conceal a field based on the content of another field using jQuery

Is there a way to hide or show a field on my website based on the value in the shopping cart? I've created a function for this, but I'm struggling with the condition. Can you help me figure out how to write it correctly? <script> $(docume ...

The Tailwind CSS classes failed to load properly within the npm package

I recently developed an Npm package using Vite with React and TailwindCSS. The package is functioning properly, but I encountered an issue when installing it in a different project – the CSS styles are not being applied. Can anyone provide guidance on h ...

Navigation bar options across various web pages

In my Next JS project, I encountered an issue with the Navbar component. By default, the Navbar elements change color from white to black when scrolling below 950px. However, I needed to make an exception for another specific page ("/lodge/page.tsx"). On t ...

The onload event for windows does not fire

I am currently working on a project that requires the use of tabbing control with flyingbox. To achieve this, I consulted the following link: After referring to the above link, I made some modifications to my project. I am retrieving details from another ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

Invoke a function in a different component following the completion of an asynchronous task in a React.js application

I am working with 2 components in my project. The first component contains a function that needs to be called after an async function in the second component completes. I am looking for a way to achieve something similar to Vue's this.$emit() function ...

Tips for switching the background image in React while a page is loading?

Is there a way to automatically change the background of a page when it loads, instead of requiring a button click? import img1 from '../images/img1.jpg'; import img2 from '../images/img2.jpg'; import img3 from '../images/img3.jpg& ...

Tips for incorporating icons in material-ui version 1.3 are as follows:

I'm feeling a bit lost when it comes to utilizing icons in the current version of material-ui. After referring to the material-ui documentation on icons, specifically regarding SVG Material icons: We offer a separate NPM package, @material-ui/icons, ...

Setting up your React Environment: A Step-by-Step Guide

I'm currently experiencing difficulties setting up my react environment. After executing the command npm create-react-app my-app, I encountered errors. The error messages are as follows: npm WARN npm npm does not support Node.js v20.12.2 npm WARN npm ...

Enhanced Bootstrap Carousel with White Background Transitions

Having trouble articulating my issue, so here's a video that should clarify: https://example.com/video I'm using a bootstrap carousel template for a full-width slider. Despite my efforts to remove the white-space transitions, they persist. Am I ...

What is the best way to prioritize theme styles in Material UI over the inherited font CSS on a webpage?

I am in the process of developing a browser extension using React with MUI. This extension will be injected into the DOM of a specific page, which includes a CSS file that contains a rule targeting h6 elements: h6 { font: inherit; } Despite explicitly s ...

Adjust the size of an image based on the smaller dimension utilizing CSS

Allowing users to upload images that are displayed in a square container in the UI presents challenges. The uploaded images can vary in size, aspect ratio, and orientation, but they should always fill the container and be centered. To address this issue, ...

Small web app encounters error 501, indicating not implemented functionality

I've been working on uploading images to an S3 bucket using react and expressjs. However, whenever I try to upload the image, I keep getting a 501 Not Implemented Error. My approach involves using axios to communicate with the endpoint created in the ...

Error encountered while attempting to save information to mongoDb collection: "Missing definition for Model"

Every time I attempt to save a model to a mongoDb collection, I encounter the error message "ReferenceError: Model is not defined". In the model file, the code appears as follows: const mongoose = require('mongoose'); const Schema = mongoose.Sc ...