Encountering issues with implementing useStyles in Material-UI components

Currently, I am working on a project utilizing Material-UI's library and encountering styling issues.

This project marks my initial venture into ReactJS and JavaScript in general. Therefore, any assistance would be greatly appreciated!

I am struggling to style my text box in the manner demonstrated in their example.

This is the code snippet:

  class AppBase extends Component {

    constructor(props) {
      super(props);
      this.state = {
          ...INITIAL_STATE
      };
  }

    classes = useStyles;

  render() {
    return (
      <Container component="main" maxWidth="md">

      <div className={this.classes.root}>
        <TextField required id="standard-required" label="Required" defaultValue="Hello World" />
        <TextField disabled id="standard-disabled" label="Disabled" defaultValue="Hello World" />
        <TextField
          id="standard-password-input"
          label="Password"
          type="password"
          autoComplete="current-password"
        />
        <TextField
          id="standard-read-only-input"
          label="Read Only"
          defaultValue="Hello World"
          InputProps={{
            readOnly: true,
          }}
        />
        <TextField
          id="standard-number"
          label="Number"
          type="number"
          InputLabelProps={{
            shrink: true,
          }}
        />
        <TextField id="standard-search" label="Search field" type="search" />
        <TextField
          id="standard-helperText"
          label="Helper text"
          defaultValue="Default Value"
          helperText="Some important text"
        />
      </div>
      </Container>
    );
  }
}

The sample I referenced can be found here: https://codesandbox.io/s/51hrm

I have exactly replicated the useStyles at the top, resulting in this outcome:

Here is how the code appears

This issue with calling useStyles in my components is not isolated, as I've encountered it multiple times.

While 'classes = useStyles;' functions correctly with some useStyles, it doesn't work with others, leaving me perplexed.

Due to the existing structure of other pages, I am hesitant to adopt Functions like the provided example.

Your assistance is much appreciated in advance!

Answer №1

When implementing the useStyles function from the provided example, remember to call it as a function. Currently, you are only storing the function in the classes variable without actually running it. Simply modify one line of code like this:

const classes = useStyles();

By doing so, you will execute the useStyles function and store the result in the classes variable. This way, you can utilize the classes constant in your jsx to style the components just like in the example:

<form className={classes.root} ...></form>

Answer №2

The useStyles hook is designed to be used inside a functional component. If you want to utilize the useStyles hook, you will need to convert your class component into a functional component.

For experimentation purposes, I have created a live sandbox for you: https://codesandbox.io/s/loving-bouman-47bek?fontsize=14&hidenavigation=1&theme=dark

The code provided below should function correctly:

import React from "react";
import ReactDOM from "react-dom";
import { Container, TextField } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    border: 0,
    borderRadius: 3,
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
    color: "white",
    height: 48,
    padding: "0 30px"
  }
});

function App() {
  const classes = useStyles();

  return (
    <Container component="main" maxWidth="md">
      <div className={classes.root}>
        <TextField
          required
          id="standard-required"
          label="Required"
          defaultValue="Hello World"
        />
        <TextField
          disabled
          id="standard-disabled"
          label="Disabled"
          defaultValue="Hello World"
        />
        <TextField
          id="standard-password-input"
          label="Password"
          type="password"
          autoComplete="current-password"
        />
        <TextField
          id="standard-read-only-input"
          label="Read Only"
          defaultValue="Hello World"
          InputProps={{
            readOnly: true
          }}
        />
        <TextField
          id="standard-number"
          label="Number"
          type="number"
          InputLabelProps={{
            shrink: true
          }}
        />
        <TextField id="standard-search" label="Search field" type="search" />
        <TextField
          id="standard-helperText"
          label="Helper text"
          defaultValue="Default Value"
          helperText="Some important text"
        />
      </div>
    </Container>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I strongly recommend transitioning to functional components over class components as functional components are deemed the future of React.

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

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

What is the best way to retrieve the id from a SelectField in material-ui with React?

I have exhausted all resources and attempted the solutions provided by others, but unfortunately I am unable to make it work. The issue at hand is that event.target.id and event.target.value are not functioning in this scenario. I have conducted some resea ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

The initial call to React's useSelector may result in returning undefined, but subsequent calls function properly

For my mini eCommerce app built with the MERN stack, I am implementing a feature where each seller can only edit or delete their own products. To achieve this, I fetch products based on the seller's id retrieved from the Redux state of the user. With ...

Jquery Menu featuring subitems aligned to the right

I am experiencing an issue with my drop-down menu in ie6. The subitems menus are shifted to the right, rendering the menu useless. Here is the HTML code: <div id="navigation"> <a href="<?php echo base_url();?>" class="singl ...

What is the process for allowing right-click to open in a new tab, while left-clicking redirects to a new page in the current tab?

In my project, I have implemented a multi-page form for users to input information. The left side menu contains items that allow users to switch between different pages while filling out the form. Currently, clicking on any of these items redirects the use ...

The process of eliminating body padding in Nuxt.js

I'm considering building a website using Nuxt.js because I've heard it's both cool and user-friendly. While I do have some knowledge of vue.js, I'm stuck on a particular issue: How can I remove the padding from the body? I understand ...

Is it possible to assign the margin-bottom property of one element to be equal to the dynamic height of a sibling element?

I am in the process of creating a website that features a fixed (non-sticky) footer placed behind the main content using the z-index property. The footer only becomes visible when the user scrolls to the bottom of the page, achieved by assigning a margin-b ...

Struggling to transfer sass variables between scss files

Within my React application, I have a specific file named _variables.scss which holds various defining variables to be utilized across different .scss files: $navy: #264653; $green: #2A9D8F; $yellow: #E9C46A; $orange: #F4A261; $red: #E76F51; $title-font: ...

Using HTML <style> in a bash script is a great way to enhance

I am attempting to eliminate the bullet points from HTML code generated by a bash script. I am currently struggling to apply the style across the entire program. Given my limited knowledge of html, I suspect that I may be misinterpreting or incorrectly p ...

Sending information to a component through navigationPassing data to a component

When attempting to move from one component to another page using routes and needing to send parameters along with it, I have experimented with passing them as state through history.push(..) like the following code. However, it does not seem to be working a ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

What criteria do web browsers use to determine the order in which to apply @media queries when there are multiple relevant queries for the device

My website requires adjusting element positioning based on specific resolutions. One example is this media query: @media all and (max-width: 385px) And another one: @media all and (max-width: 500px) The device I am using has a width below 385px, but i ...

Display various elements depending on the size of the screen within Next.js

My goal is to display a component differently depending on whether the screen width is less than 768p or not. If the width is under 768p, I want to show the hamburger menu. Otherwise, I want to display the full menu. This is the code snippet I am using. ...

What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the i ...

Click on an image to dismiss a material-ui dialog

Trying to include a clickable image to close a material-ui dialog, but encountering an issue where the onClick event is not responding. The props.onRequestClose function works fine when clicking outside of the dialog. What could be causing this problem? ...

Could you please clarify the type of event on the onInputChange props?

I am encountering an issue with using React.ChangeEvent on the mui v4 autocomplete component as I prefer not to use any other method. However, I keep getting an error indicating that the current event is incompatible. const handle = (e: React.ChangeEv ...

Simple user interface height to occupy the entire browser window

Adding Tabs Dynamically ... I am attempting to design a layout using this example ... however, the issue is that the page does not utilize the full height and width of the available space... I have attempted adjusting the width and height to 100% of the ...

Content overflowing beyond the boundaries of the parent DIV in Internet Explorer 6

Take a look at the code snippet below: <div style="width: 50px; border: 1px solid green;"> <div style="position: absolute;"> add whatever text you'd like </div> </div> The display in modern browsers (such as I ...

Updating the value property of an object within a loop dynamically in React

At the moment, I am utilizing an array of objects called "mainArr" as shown below, I have implemented a loop inside a function to filter object properties, but I want to dynamically replace obj.name with obj."param" based on the parameter passed. Both nam ...