Choosing between classes and styles for styling components in ReactJS

Can you explain why the call to the classes object works in the code below, rather than to the styles object defined as a const at the beginning?

For instance, take a look at this demo:

className={classes.button}

The above line functions correctly. However, it appears that it should actually be:

className={styles.button}

Is there a specific classes object being referenced somewhere? If so, where is it declared? The structure suggests a this.props.classes object, but no props are passed to <Demo /> when invoked in index.js.

Could someone shed some light on this situation?

Click here for the live demo
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  button: {
    margin: theme.spacing.unit,
  },
  input: {
    display: 'none',
  },
});

function OutlinedButtons(props) {
  const { classes } = props;
  return (
    <div>
      <Button variant="outlined" className={classes.button}>
        Default
      </Button>
      <Button variant="outlined" color="primary" className={classes.button}>
        Primary
      </Button>
      <Button variant="outlined" color="secondary" className={classes.button}>
        Secondary
      </Button>
      <Button variant="outlined" disabled className={classes.button}>
        Disabled
      </Button>
      <Button variant="outlined" href="#outlined-buttons" className={classes.button}>
        Link
      </Button>
      <input
        accept="image/*"
        className={classes.input}
        id="outlined-button-file"
        multiple
        type="file"
      />
      <label htmlFor="outlined-button-file">
        <Button variant="outlined" component="span" className={classes.button}>
          Upload
        </Button>
      </label>
    </div>
  );
}

OutlinedButtons.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(OutlinedButtons);

Answer №1

Upon reviewing this particular line:

export default withStyles(styles)(OutlinedButtons);

I am confident that the solution to your query lies within. Material UI introduces a function withStyles which receives a styles object and then outputs another function that further accepts a component to generate a new one. This concept is recognized as a Higher Order Component and can be extensively explored on the React documentation.

By examining the source code of withStyles linked above, you will notice a crucial line where it renders the provided component as follows:

return <Component {...more} classes={this.getClasses()} ref={innerRef} />;

This action assigns the classes prop, ensuring its availability for any component exported using withStyles.

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

An interesting result from using fs.appendFile: the mysterious [object Object]

When utilizing console.log, the output of req.query (request.query) appears correct as { name: 'sean', comments: 'Hey' }. However, the issue arises when attempting to write this data to a file using fs.appendFile, as it ends up being wr ...

Tips for customizing the design of the material-ui slider

Is it possible to customize the colors of different elements in the slider, like the handle and track sections? Or is there a way to hide the slider while still keeping its functionality so I can create my own design based on the slider value? I am not su ...

I'm encountering an error in my terminal while running the code

ERROR *Server started on port 4000 Database ErrorMongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 (node:1616) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 at NativeConnection.Connec ...

Employing the "div" element to target in CSS styling

I'm dealing with a document structure that is consistent across multiple pages. HTML: <ul> <li> <div> <img src="" /> </div> </li> </ul> Presently, there is a border aroun ...

Using jQuery and PHP to send a dynamic form through AJAX

I'm currently working on a pet registration form where users can add new pets. When a user clicks the "add pet" button, I use jQuery to clone the pet section of the form and give each cloned section an id like #pet-2, #pet-3, and so on. Although my ...

The ability to update a variable passed through the state in Link is restricted

Currently, I am in the process of updating the theme in my App using useState. The updated theme is passed to the Topbar Component as a prop, triggering console.log() every time it changes. The theme is then passed from the Topbar to the AboutMe Component ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Enabling visibility of overflowing text in dynamically inserted divs without using scroll bars

Is there a way to set the text overflow to visible without scroll bars in dynamically added <div>s? Despite what the documentation says, it doesn't seem to be the default behavior and I'm struggling to understand why. Adding text directly t ...

Retrieving device information through JavaScript, jQuery, or PHP

Looking to build a website that can identify the device name and model of visitors accessing the page from their devices. ...

Updating a value in Expressjs variable is not working as expected

In the code snippet below, I have declared a variable called sumOfRevenue. I assigned it a value of 10 in the router, but when I try to print its value, it comes out blank. Can you please help me understand why it's not showing as 10? Please review t ...

Using express.static can cause an issue with a Nodejitsu application

I'm completely puzzled by this issue that keeps cropping up. Whenever I try to add a static path to my app, I encounter an error on the hosting platform I use called "nodejitsu". The error message indicates that the application is not functioning prop ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Vue.js - updating npm to patch version with unclean git working directory

I recently followed a tutorial on how to publish packages to NpmJS. However, I encountered an error when trying to update the package after making changes to the README.MD: npm version patch npm ERR! Git working directory not clean. npm ERR! A .gitignore ...

utilize ng-include in angularjs to include a page

For some reason, I am having trouble including a file using ng-include. The file is supposed to be included when a button is pressed: <button type="submit" class="btn btn-primary" ng-click="getPartial()">Compare</button> This is the function ...

Require assistance to resolve variable scope problems

Having trouble accessing the names array within the driver.executeScript method. Any suggestions on how to resolve this issue? var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; var driver = new webdri ...

Determining If Props Have Been Undefined In React

Greetings and thank you for taking the time to read this: I am currently working through a tutorial that can be found here: My issue lies in the creation of an author, where the application is trying to load the URL of the current author's ID, which ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...

The z-index property does not seem to function properly when used in conjunction

I am experiencing an issue with the z-indexes of two divs: one with default positioning and the other with a fixed position. No matter how I adjust the z-index values, it appears impossible to make the fixed-positioned element go behind the statically pos ...