A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implement styling in TypeScript using the Material-UI library.

I diligently followed the instructions on https://material-ui.com/guides/typescript/ and created a theme:

import { createMuiTheme } from "@material-ui/core/styles";

export default function theme() {
  return createMuiTheme({
  palette: {
    primary: {
      main: "#607D8B",
      light: "#CFD8DC",
      dark: "#455A64",
      contrastText: "#FFFFFF"
    },
    secondary: {
      main: "#7C4DFF",
      contrastText: "#212121"
    }
  }
})};

I also created styles:

import { green, red } from "@material-ui/core/colors";
import { createStyles, withStyles } from "@material-ui/core/styles";
import { Theme } from '@material-ui/core';

const useStyles = (theme: Theme) => createStyles({
  // Various style definitions
});

export default withStyles(useStyles);

Next, I tried implementing these styles on a component:

// Component implementation code here

The error message I encountered is:

An argument of type 'Theme' is not assignable to parameter of type 'ComponentType<{ }>

If I try casting the type using:

const classes = useStyles<any>(theme);

It then raises an issue about the className property not existing, like classes.table, for example.

I find this whole situation very confusing and would greatly appreciate any help or insight!

Answer №1

To resolve the issue, I created the following styles file:

 const customStyles = makeStyles((theme: Theme) => createStyles({
  main: {

Answer №2

Here is some documentation on createStyles and makeStyles

After testing the code provided below, I was unable to replicate the type error you mentioned.

import { Theme, useTheme, makeStyles } from "@material-ui/core";

const useStyles = makeStyles((theme: Theme) => ({
  root: {}
}));

export default function App() {
  const theme = useTheme<Theme>();
  const classes = useStyles(theme);
  return (
    <div className="App">
      <h1 className={classes.root}>Theme</h1>
    </div>
  );
}

Feel free to try it out online:

https://codesandbox.io/s/kind-robinson-3j05i?fontsize=14&hidenavigation=1&theme=dark

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

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

I am experiencing difficulties with the deletion query function in Supabase

async function removeImage(imageName) { const { result, err } = await supabase .storage .from('img') .delete([ CDNURL + "/" + imageName ]) console.log(result) I wrote this code to delete an image b ...

.scss compiling with errors

Recently, I embarked on a new Vue(3) project. Within this project, I have set up some basic styling in the App.scss file and created a HomeView.vue with a corresponding HomeView.scss file (located in the /src/views/Home directory). The styling from both fi ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

Elevated Drawer Navigation Menu Switch pushes content down to reveal active links

I am currently facing challenges in creating a top drawer navigation menu for a mobile device. My inspiration is the navigation menu utilized in the Google+ iPhone application. When the menu is clicked on, my goal is to have it slide down and push the con ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Leveraging the :has pseudo-class in Tailwind along with adjacent sibling selectors

My CSS code is working perfectly as intended. [data-type='transfer']:has(+ [data-type^='sale_']) { opacity: 0.25; } This CSS snippet targets elements with data-type="transfer" that are next to elements containing data attri ...

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

Animating two elements on scroll at specific point with speed problem

Trying to create an animation with two different images once a user reaches a specific point on the page. The animation works, but there is an issue when using a trackpad - the movement appears slow compared to scrolling with a mouse. I've already att ...

Exploring the use of React material-ui Drawer list to render various components onClick in your application

Working on designing a Dashboard with the React material-ui package involves implementing an App bar and a Drawer containing a List of various items. The objective is to render the corresponding component inside the "main" tag of the Drawer upon clicking a ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Watir /Cucumber Element not found: dd-field div.dd-arrow-box (CSS Selector)

Chief complaint: The element cannot be located using CSS Selector Custom Css path: html.ng-scope body.ng-scope div.snap-content div.content-container div.ng-scope div.content-box div div.cb-landing-module div.deposit-acct-box div.dropdown div.dd-field ...

What could be causing my CSS relative positioning to malfunction?

I am struggling to adjust the positioning of my divs using relative and absolute properties. Any advice on how to resolve this issue would be greatly appreciated. Thank you. Example Code: <div id="game"><img src="gta-game.jpg" height="100" width ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

Invoke the componentDidMount() method in a React Component that is not a subclass of React.Component

I have a react component that I render later in my index.js file index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> ...

A guide to sharing session variables with express views

Struggling to access session variables in EJS views and encountering various challenges. To locally access req.session, I've implemented middleware as outlined in this guide on accessing Express.js req or session from Jade template. var express = re ...

Transmit data to PHP servers

When the button in my HTML is clicked, it should trigger a query in a PHP file that will display the results. However, the button does not seem to be working as expected. What could be causing this issue? Here is the code I have tried: <?php $reply_ ...

Obtain a reference to a class using a method decorator

My goal is to implement the following syntax: @Controller('/user') class UserController { @Action('/') get() { } } Now in the definition of decorators: function Controller (options) { return function(target: any) { let id ...

Tips for retrieving console data in VueJS Data

Is there a way to review data from a form component in the console without vue taking any action? I need to receive external data and fill in the fields accordingly. I attempted to set a value using document.getElementsByName("nfe.codigo")[0].value = "000 ...

Problem with onblur and onchange events not being triggered in input tag

After encountering this issue, I came to the realization that the events onblur and onchange function properly. However, I noticed that if your page contains only ONE <input type="text" onblur="loadXMLDoc()"> Change Content</input> The behav ...