Applying Material UI class in React: Troubleshooting an error with your hook call

Recently, I have started using React and encountered an issue with a hook call. I understand the root cause of the problem but unsure how to resolve it without starting from scratch. Here is the snippet of the code:

import { Fragment, PureComponent } from "react";

//Test Imports
import { Input, makeStyles } from '@material-ui/core';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import testDaten from './testData.js';
import { Link } from "react-router-dom";
//

 //Test
 const UseStyles = makeStyles((theme) => ({
    root: {
      flexGrow: 1,
      marginTop: '100px',
      marginLeft: '100px',
      marginRight: '50px',
      
    },
  
    grid: {
      color: theme.palette.text.primary,
    },
    paper: {
      padding: theme.spacing(2),
      textAlign: 'center',
      color: theme.palette.text.primary,
    },
    photo: {
      height: '200px',
      width: '200px',
    }
    }));
    //

class Select extends PureComponent {

    state = {
      options: [
        {
          name: 'Select…',
          value: null,
        },
        {
          name: 'A',
          value: 'a',
        },
        {
          name: 'B',
          value: 'b',
        },
        {
          name: 'C',
          value: 'c',
        },
      ],
      value: '?',
    };
  
    handleChange = (event: any) => {
      this.setState({ value: event.target.value });
    };
       
    render() {

   

    const { options, value } = this.state;
    const classes = UseStyles();

        return (
          <Fragment>
            <select onChange={this.handleChange} value={value}>
              {options.map(item => (
                <option key={item.value} value={String(item.value)}>
                  {item.name}
                </option>
              ))}
            </select>
            <h1>Favorite letter: {value}</h1>
            
            {testDaten.map((item, key) => {
            if(value != null){
            return (
            <Grid item xs={4} sm={4} key={item.id}>
              <Input value={item.id} type="number" id="idTest"/> 
              <Paper className={classes.paper}> Visitor ID: {item.id} </Paper>
              <Paper className={classes.paper}> Name: {item.firstName} {item.lastName}</Paper>
              <Paper className={classes.paper}> Type of Evidence: {item.evidenceType} </Paper> 
              <Paper className={classes.paper}>   <Link to={`/toAssessTest/${item.id}`}>More information</Link> </Paper> 
            </Grid>
          )
        }
          })}
          </Fragment>

          
        );
      }
    }

    export default Select;

I am facing a hook error within the render function due to const classes = UseStyles(); --> as far as I understand, this happens because it's not at the top level. However, I'm not sure how to apply Material UI classes without it. Any assistance on this matter would be greatly appreciated.

Thank you!

Answer №1

Transform class into a functional component or utilize Hoc(withstyles) from materialui

The code below has been converted to use withstyles to access styles from classes props

import { Fragment } from "react";
import { Input, withStyles } from "@material-ui/core";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
import testDaten from "./testData.js";
import { Link } from "react-router-dom";

const styles = (theme) => ({
  root: {
    flexGrow: 1,
    marginTop: "100px",
    marginLeft: "100px",
    marginRight: "50px",
  },

  grid: {
    color: theme.palette.text.primary,
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.primary,
  },
  photo: {
    height: "200px",
    width: "200px",
  },
});

const Select = ({ classes }) => {
  const [options, setOptions] = useState([
      {
        name: "Select…",
        value: null,
      },
      {
        name: "A",
        value: "a",
      },
      {
        name: "B",
        value: "b",
      },
      {
        name: "C",
        value: "c",
      },
    ]);
    
  const [value, setValue] = useState("?");

  const handleChange = (event: any) => {
    setValue(event.target.value);
  };

  return (
    <Fragment>
      <select onChange={handleChange} value={value}>
        {options.map((item) => (
          <option key={item.value} value={String(item.value)}>
            {item.name}
          </option>
        ))}
      </select>
      <h1>Favorite letter: {value}</h1>

      {testDaten.map((item, key) => {
        if (value != null) {
          return (
            <Grid item xs={4} sm={4} key={item.id}>
              <Input value={item.id} type="number" id="idTest" />
              <Paper className={classes.paper}>
                {" "}
                Besucher-Id: {item.id}{" "}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                Name: {item.vorname} {item.nachname}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                Nachweisart: {item.nachweisart}{" "}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                <Link to={`/zuBewertenderTest/${item.id}`}>
                  More Information
                </Link>{" "}
              </Paper>
            </Grid>
          );
        }
      })}
    </Fragment>
  );
};

export default withStyles(styles)(Select);

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

What is the best way to access an object's key within an array using TypeScript?

How can I access the key values of the objects stored in a predefined array? const temp = [ { key: "name", value: "mike" }, { key: "gender", value: "male" }, ]; I am interested in retrieving the key values, such as name and gender, from the objects wi ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

Having trouble with the display of styles on Material UI Cards?

I am currently attempting to customize the default Material UI classes by using useStyles and applying a classname of titleSection. My goal is to make the titleSection bold and in Roboto font, but unfortunately, those styles are not being applied. Below i ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

Personalized Input Field with an icon placed at the beginning of the field, featuring the outlined variant design in material-ui

Hey there! I've been working on a project where I'm trying to add an icon inside the TextField component using material-ui. If you're familiar with Material UI, then you know what I'm talking about. I decided to stick with Version 4 fo ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

Problem integrating 'fs' with Angular and Electron

Currently, I am working with Angular 6.0, Electron 2.0, TypeScript 2.9, and Node.js 9.11 to develop a desktop application using the Electron framework. My main challenge lies in accessing the Node.js native API from my TypeScript code. Despite setting "com ...

Updating the state in React is causing significant delays

In my React project, I am utilizing the pdf-lib (JS library) for some intensive tasks using async/await. My goal is to update a progress bar by modifying the state. However, when I use setState within a setTimeout, the state changes are not reflected unt ...

The Typescript error message states that the type '{ onClick: () => void; }' cannot be assigned to the type 'IntrinsicAttributes'

I'm a beginner in Typescript and I'm encountering difficulties comprehending why my code isn't functioning properly. My goal is to create a carousel image gallery using React and Typescript. However, I'm facing issues when attempting t ...

Error message from webpack: It appears you are missing a necessary loader to handle this specific file type

I'm struggling with building my server.ts typescript file for the backend. I have some imports, but my app is not building. Here is a snippet from my typescript file: import * as Express from 'express' import * as Session from 'expres ...

Ways to eliminate duplicate objects from an array using Angular 6

I'm having trouble removing duplicate value objects in an array and it's not working as expected. I believe the duplicate function is functioning correctly, but the changes are not being reflected in the li list. Can you pinpoint where I need to ...

Is there a way for me to verify that the key of one object is a subset of the keys of another object?

export const masterKeysObject = { MAIN: 'main', REDIRECT: 'redirect', DASHBOARD: 'dashboard', USER_ID_PARAM: ':userId', CREATE_NEW: 'create_new' } as const; type MasterKeys = keyof type ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

The service that offers an Observable on a specific subject is not receiving any notifications

The EventSpinner component is designed to subscribe to icons provided by the EventsService. @Component({ selector: 'event-spinner', template: ` <div class="col-xs-5"> Test <i class="fa fa-2x" [ngClass]="{'fa-check' ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

Exploring the functionality of material-UI tabs in a react environment

One challenge I often encounter is figuring out how to effectively utilize Material-UI tabs. With a plethora of posts available, each targeting different versions of Material-UI and offering varying implementation methods, it can be quite confusing. The w ...

Problem with Typescript compilation in lerna package

Presently, my project is structured with lerna/react/TS setup as shown below: . ├── lerna.json ├── package.json ├── packages │ ├── patient │ │ ├── package.json │ │ ├── src │ │ │ └── ...