Incorporating Material-UI themes within styled components

Trying to incorporate theme spacing value in a styled component but facing issues. Initially, the style was applied to the button, but now it is not working as expected.

You can view the problem here: sandbox.

import React from "react";
import styled, { ThemeProvider } from "styled-components";
import {
  createMuiTheme,
  ThemeProvider as MuiThemeProvider,
  darken
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: "#6772e5"
    }
  },
  spacing: 8
});
const StyledButton = styled(Button)`
  ${({ theme }) => `
    background-color: ${theme.palette.primary.main};
    color: #fff;
    box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
    padding-left: 20px;
    padding-right: ${theme.spacing(2)};
    font-size: 13px;
    &:hover {
      background-color: ${darken(theme.palette.primary.main, 0.2)};
    }  
  `}
`;

export default function App() {
  return (
    <MuiThemeProvider theme={customTheme}>
      <ThemeProvider theme={customTheme}>
        <StyledButton>Customized</StyledButton>
      </ThemeProvider>
    </MuiThemeProvider>
  );
}

Answer №1

If your styled-component styles are being overridden by the default JSS styles, you can change this behavior. By default, JSS styles are injected at the bottom of the head element (which has higher CSS specificity). To prioritize styled-components, place your component tree inside the

<StylesProvider injectFirst>
tag. Check out the documentation on controlling priority.

// ensure styled-component takes precedence over JSS style
<StylesProvider injectFirst>
  <MuiThemeProvider theme={customTheme}>
    <ThemeProvider theme={customTheme}>
      <StyledButton>Customized</StyledButton>
    </ThemeProvider>
  </MuiThemeProvider>
</StylesProvider>

https://codesandbox.io/s/67232779using-material-ui-theme-in-styled-component-y3ljg?file=/src/App.tsx

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

Styling the Container Component in ReactJS

I need to apply some styling to the "Forms_formline__3DRaL" div (shown below). This div is generated by a component, but it seems that the style I want to add is being applied to the input instead of its parent div. How can I use ReactJS to set the style " ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

Is there a way to retrieve data from the host URL within the getStaticPaths function in Next.js?

In my Next.js application, there is a serverless function responsible for fetching data from the host. The host URL is configured in a .env file where it is set to http://localhost:3000/api/data during development and https://productionurl.com/api/data in ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Encountering an issue while trying to update my Electron app, receiving an error message indicating that

I am in the process of updating an Electron app that is two years old and I encountered a challenge. I had to update the syntax by replacing window.require() with CreateBrowserWindow to make the app render in a new window instead of in the browser at local ...

The alignment of the content within a div is mismatched compared to a div that doesn't have any

Can you figure out why the element with content is out of order compared to the other elements without content in the code below? This issue seems to disappear when all elements have content. Any insights on this peculiar behavior? (Thank you in advance fo ...

Is it possible to incorporate a different website font into an email template?

Currently working on an email template and looking to match the font with my website. Is there a method to ensure my site's font carries over into the email template? Provided below is the HTML code: <!DOCTYPE html> <html> <head> ...

Problem with transitions not working properly in Vue.js.The issue

Experiencing an issue with the Vue.js transition feature. Check out this link for reference. When the transition enters, it works smoothly, but when transitioning out, it's not functioning properly. File: genetic.vue <transition name="slide-f ...

Adjust the response using React.js

How can I change or eliminate the response headers in my react.js application? Specifically, is there a method to remove the "X-Powered-By" header? Is it possible to achieve this in react.js without using express? ...

The client-side state does not retain information from the server upon page refresh

After creating a new store, the client-side state is not being properly updated from the server. To view the issue in action, visit: https://codesandbox.io/s/vibrant-aryabhata-l29r2b Here are the steps to reproduce the behavior: Access the app using the ...

Customize the List Box Appearance for a Specific HTML Item (Option)

I am working on achieving a specific behavior. When using a listBox (or comboBox), the first element (such as "choose one") should have a unique style. Here is an example of code to test: <style type="text/css"> .testX {font-style: italic;} </ ...

What could be causing my fixed header to disappear in Safari 5?

I am experiencing a strange issue with my fixed header on Safari 5 for iPad. The header disappears once it scrolls down to a certain point, even though it works fine in IE, Firefox, Chrome, and the latest version of Safari. Has anyone else encountered this ...

A blank page appears when deploying a React app on GitHub pages

As a beginner with react, I recently completed building my first application. Now, I am facing an issue while trying to deploy it on Github Pages – the page appears completely blank. Here are the steps I have taken so far: Installed gh-pages using: npm ...

Eliminating an item from an array with the help of React hooks (useState)

I am facing an issue with removing an object from an array without using the "this" keyword. My attempt with updateList(list.slice(list.indexOf(e.target.name, 1))) is only keeping the last item in the array after removal, which is not the desired outcome. ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Tips for maintaining consistent webpage layout across various screen sizes

Although this method may seem outdated, I have always been intrigued by how it was accomplished. In the past, before websites became responsive, pages would simply shrink down to fit on mobile devices without adjusting their appearance. How was this achie ...

"Displaying an array using React Hooks' useState causes the content to

I want to enhance my image uploading functionality in useState by implementing a specific function. Once the images are uploaded, I need to render them on the page. However, I am facing an issue with rendering the returned array. Here is the current code ...

The command 'yar' is not a valid cmdlet that can be recognized

After running the installation code for Yarn, I received this message. How can I properly install Yarn on my project using Windows 11? npm install -g yarn changed 1 package, and audited 2 packages in 922ms found 0 vulnerabilities (yar : The term 'ya ...

How can a function in one React component be invoked from another component?

Currently in my React project's App.js, I am calling the this.searchVenues() function in my return statement. It works, but the implementation is messy and I know there must be a more efficient way to achieve this. The searchVenues() function is locat ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...