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

Having trouble saving the server-sent cookie on the browser. Employing Axios on the client side

Here is my express code where I am utilizing express-session to manage storage and work with cookies. Since version 1.5.0, the module no longer requires cookie-parser to handle storing the cookie in req/res. The session data is stored in a PSQL database h ...

Issue with anchor tag not functioning properly within toggle div

Can you please help me troubleshoot why the anchor tag is not functioning properly within my div elements? When I click on the first div, the second div is displayed but the anchor tag inside the first div does not seem to be working. <script> $(&ap ...

Enhancing Mocha and Chai tests: Exploring ways to increase strictness

While working with Mocha and Chai, I have come across numerous unreliable tests. I want all of these tests to fail. Similar issues on StackOverflow are often due to async problems and not using done(). Regardless, even if that were my problem, I would stil ...

Tips for integrating Server-Side Rendering into an already established React.js app running on Express.js

I am currently working on a React application and I am looking to add SSR using Express.js. Initially, I made a mistake by creating a repository with just a frontend folder containing the entire React app with typescript, babel, and webpack configurations ...

What is the best way to dynamically adjust the height of an iframe based on its changing content

My webpage contains an iframe that loads content dynamically, and I want to center it on the page based on its height. The issue I'm facing is that while my code works well for increasing content heights, it fails to recognize when the content size de ...

Implement jQuery to close multiple div elements

My dilemma involves a series of divs with different manufacturer IDs listed as follows: manufacturer[1], manufacturer[2], manufacturer[3], ... etc ... In attempting to create a JavaScript for loop to hide each div, I discovered that it was not achievab ...

Issues regarding the sizing of fonts on mobile devices

Struggling to create a responsive site that looks good on high dpi mobile devices? You're not alone. No matter how you adjust your h2 and p text sizes, they seem to be the same size when viewed in portrait mode on certain devices like the Galaxy S4. E ...

Guide to integrating a static page with personalized CSS and JavaScript resources within a Rails project

Currently, I am developing a simple Rails application (using Rails version 4.1) and I am looking to incorporate a static page into it. The static page is structured as follows: | |- index.html |- css folder |-- (various css files) |- js folder |-- (some j ...

Adding a CSS link to the header using JavaScript/jQuery

Is there a way to dynamically inject a CSS link located in the middle of an HTML page into the head using JavaScript? <head> ... styles here </head> <body> code <link href='http://fonts.googleapis.com/css?family=Lato:400,300, ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Utilizing React JS to Export Axios Response

I have an getAllUsers.js File that retrieves all users from the API. import axios from 'axios' export const fetchData = async () => { let response try { response = await axios.get('http://127.0.0.1:8000/api/users') } catc ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

Can child elements be centered using their pseudo-elements using CSS alone?

Consider the code snippet below: <div class="example-container"> <p class="example">a</p> <p class="example">bbb</p> <p class="example">cc</p> </div> and the cor ...

I seem to be having trouble with the Clearfix - the elements at the bottom are overflowing the container

Hey there! I'm having some trouble with my website, specifically at the bottom where the letters and hr line are overflowing the container. I thought about using a clearfix, but it doesn't seem to be working as expected. I even tried adding an ov ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

Checkmate with React Native's Checkbox Component

I have implemented the React Native Elements CheckBox inside List Items within a Flat List. import React, { Component } from "react"; import { View, Text, StyleSheet, FlatList } from "react-native"; import axios from 'axios&apo ...

Encountered an issue with retrieving the property "tagName" of null during Razorpay payment integration in a Next.js application

I encountered a tagName of null error while integrating Razorpay. The issue seems to be related to the head manager. https://i.sstatic.net/b4zTP.png For those interested, here is the link to the Github repository: https://github.com/rajatgalav/razorpay-d ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...

Testing the functionality and reliability of Enzyme and React components through unit

I am working on a React functional UI component that receives two props, with the second prop being a function passed down from its parent component. When the onClick event is triggered, it calls this delegated function in the parent container component, w ...

configure redirects for specific file extensions based on regular expressions

Attempting to create a redirect rule in next.config.js to send all requests with .pdf extension to an external URL is resulting in the following error. Error encountered while parsing `/:file(.(pdf)$)` https://err.sh/vercel/next.js/invalid-route-source Rea ...