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

The CSS Grid extends vertically beyond its bounds, rather than activating the overflow-y property

Why does the grid blow out in the following snippet? The grid has a lime green border, each child has a dotted red border, and you can see the dotted red extends beyond the lime grid border. The .child2 should be made scrollable to prevent the grid from bl ...

CSS vertical alignment: Getting it just right

I am currently using Bootstrap and below is a snippet of the code I have implemented. <div class="row"> <div class="col-lg-6"><img src="#" alt=""></div> <div class="col-lg-6"> <h2>Heading</h2> ...

The Boostrap card-deck appears to be see-through and malfunctioning

This problem has been puzzling me for quite some time now, and I just can't seem to find the solution! Kindly disregard the other language and code - the card is located under the jumbotron. (To access the link, remove spaces: https://code pen.io/ano ...

Split the content of a textarea before it reaches the next element

I have a textarea in my html file and I am trying to prevent the text from overlapping with an emoji icon button. I would prefer not to use a z-index for the emoji as it may cause issues with other elements on the page. Below is the code snippet: HTML & ...

Unable to utilize await within a then statement to make a subsequent API call in a React application

Here is my scenario: I am making a call to one API, and in the `then` section of that API call, I am making another API call. The output of the first API will be passed as input to the second API. await axios .post(process.env + '/certificates/uplo ...

Storing a link as a variable in React: A guide

As someone new to programming, I am trying to achieve the following goal: Whenever a list item is clicked, I want it to redirect to another page. Here's what I have in mind: I have a side panel with a list of items. Clicking on any item should take ...

Difficulty arises with z-index when hover effects are applied to clip-path shapes

I'm encountering an issue where I am attempting to make two clip path polygons overlap each other when hovered over by the mouse. I have been using z-index values and trying to adjust them based on which overlay is being hovered over, but unfortunatel ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

React Hook Form is flagging missing dependencies in the useEffect function

Before posting this question, I made an effort to search for a solution on Google. However, I am puzzled by the warning that the linter is giving me regarding my code. The warning message reads: ./components/blocks/Contact.tsx 119:6 Warning: React Hook us ...

Maintaining Aspect Ratio and Adding Letterboxes with Next.js Image

In my Next.js app, there is a section dedicated to displaying selected photos from a gallery. It's crucial for this area to maintain a fixed size of 566px*425px as users navigate through images or when a photo is loading. While the layout is responsiv ...

Is it necessary for me to utilize Parallel Routes in Nextjs 13?

Hello everyone, I've recently delved into the world of Next.js version 13 and I have a question that's been boggling my mind. According to the documentation, Next.js is used for displaying one or more pages within the same layout. But can't ...

Alignment of inputs remains stubbornly off-center despite floating left

My main goal is to have all my inputs aligned to the left for a clean and organized look, similar to the image provided below: Despite my efforts to float the inputs and paragraphs to the left, I am facing an issue where they do not align properly. Instea ...

The issue arose with NextJs 13 and Framer Motion where the module 'v8' could not be resolved

I keep encountering this persistent error in my app directory while attempting to implement page transition animations with framer motion. Despite my efforts, I continue to come across the v8 error. Resources on resolving this issue are scarce - does anyon ...

The Axios post feature seems to be struggling with processing the returned data

Currently, I am in the process of uploading images to Cloudinary and my main objective is to retrieve the image url once it has been successfully uploaded. The issue I am facing is that although the upload is functioning correctly and I can see the URL log ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...

Show the date and time in a visually appealing way by using HTML and JavaScript in an HTA application with scrolling effects

I have the following JavaScript code to show the current date in the format Mon Jun 2 17:54:28 UTC+0530 2014 within an HTA (HTML application). Now, I would like to display it as a welcoming message along with the current system date and time: Mon Jun 2 17: ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

Utilizing the 'container' property in a React.js React-Bootstrap modal

How can I open a modal within a designated container using the native property "container"? Whenever I specify the class name of the container element, I encounter an error TypeError: Cannot use 'in' operator to search for 'current' in ...

When the screen is at mobile width, elements with the class "Responsive" are hidden using the display:none; property. These elements can be

Hey there! So, I've got this cool interactive banner on my website. It features 2 slider sections with some awesome products on the right side. The layout is responsive, meaning that when you switch to a mobile screen size (around 515px or less), the ...

a graphical representation of data organized in tabular form using

I am trying to develop a game where I need to generate a map using PHP. The goal is to create 100 table boxes in a specific pattern, but so far my attempts have not been successful... $field = 100; echo "<table border='3px' dir='ltr&apos ...