Issue with applying className to ToggleButton component in React with Material-UI

When utilizing React and Material UI, my goal is to efficiently apply styles to a group of ToggleButtons.

At the moment, I am only able to specify the style prop for each individual ToggleButton in order to achieve the desired styling.

I am attempting to use className={...} instead as a cleaner solution.

However, I have discovered that this approach does not yield the expected results with ToggleButton components:

import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';

import useStyles from './styles'; 


const DashboardSettings = () => {

  const classes = useStyles(); 

  return (
    <Fragment>
      <Paper className={classes.paper} elevation={10}> // this works fine
        <Typography variant="h4" gutterBottom>
          Settings
        </Typography>
        <br />
        <br />
        <Grid spacing={3} container>
          <Grid xs={12} item>
            <Grid container>
              <Grid item xs={12}>
                <p>Holiday(s): </p>
              </Grid>
              <Grid item xs={1}></Grid>
              <Grid item xs={10}>
                <ToggleButtonGroup
                  // value={formats}
                  onChange={() => {}}
                  // fullWidth
                  aria-label="text formatting"
                  mt={10}
                >
                  <ToggleButton value="mon" className={classes.toggleButton}> // however, this does not work!
                    <p>Monday</p>
                  </ToggleButton>        

                  <ToggleButton value="mon" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>  
                    <p>Monday</p>
                  </ToggleButton>               

                  <ToggleButton value="tue" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Tuesday</p>
                  </ToggleButton>

                  <ToggleButton value="wed" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Wednesday</p>
                  </ToggleButton>

                  <ToggleButton value="thu" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Thursday</p>
                  </ToggleButton>

                  <ToggleButton value="fri" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Friday</p>
                  </ToggleButton>

                  <ToggleButton value="sat" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Saturday</p>
                  </ToggleButton>                                        

                  <ToggleButton value="sun" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
                    <p>Sunday</p>
                  </ToggleButton>

                </ToggleButtonGroup>
              </Grid>
              <Grid item xs={1}></Grid>
            </Grid>
          </Grid>


  )


}


In the file ./styles.js:

import { makeStyles } from '@material-ui/core'; 

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(3),
    marginBottom: theme.spacing(3),
    padding: theme.spacing(20),

    [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: {
      marginTop: theme.spacing(6),
      marginBottom: theme.spacing(6),
      padding: theme.spacing(3),
    },
  },

  toggleButton: {
    marginRight: "5px", 
    marginLeft: "5px", 
    color: "#000000",
    backgroundColor: "#FFFFFF"
  },

})); 

export default useStyles; 

Why is the above method not effective? Take a look at the preview: https://i.sstatic.net/1Iy2k.png

Is there a more efficient way to apply styles to these buttons?

Answer №1

These elements are not traditional DOM (Document Object Model) components. Instead, they act as a container for DOM elements and pass values to element attributes through props. If props are not provided.

Furthermore, it is possible that when applying styles through className, the directly applied style to the element may take precedence over the class-based styles. In such cases, using decorators like !important is recommended. For example:

height: '120px !important',

export const ToggleButton = (props) => {
      //Only pass props that are used here
      //Here, I am utilizing className as props and passing it to the original elements
      //In your case, there is no className attribute
      const {onClick, style, className, children, text, type} = props;

      return (
          <button onClick={onClick} style={style} className={className} type={type>
            {children || text}
           </button>
      )
    }

If a certain prop is not available, then you cannot pass it to the component if there is no implementation for it.

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

Dynamic SVG circles with timer and progress animation

Is there a way to modify the following: var el = document.getElementById('graph'); // get canvas var options = { percent: el.getAttribute('data-percent') || 25, size: el.getAttribute('data-size') || 220, lineW ...

One specific request is encountering an issue with the 'Access-Control-Allow-Origin' header not being present on the requested resource, while the other API requests are functioning properly

I am currently facing a strange issue that has me trapped. I have configured CORS on my Nodejs backend using the CORS package const whitelist = ['https://www.domainname.co/', 'https://admin.domainname.co/','https://organizers.doma ...

Send users directly to a designated section of a different route when they click a button

I have my main page located at localhost with a footer that contains a contact button. When clicked, this button is meant to redirect the user to the contact section on another page at localhost/home. Both sections have a specific reference called ref. How ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

Having trouble refreshing the page after making changes to the redux state

On the '/dashboard/gdrive' page, I am able to retrieve a list of Google Drive files. There is also an option to upload a new file. However, after uploading, while the Redux state confirms that the new file has been stored in the state, I encounte ...

When attempting to execute the "npm run start" command in a ReactJS environment, an error message appeared

'react-scripts' command is not being recognized as a valid internal or external command, able to use program or batch file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] start: react-scripts start npm ERR! Ex ...

React Native: Unable to print to the console with console.log()?

I find myself in a peculiar situation where I am attempting to track down a bug and log it on the console without any success so far. The post is requesting more information, but unfortunately, there isn't much to provide. Right now, my main focus is ...

I am attempting to set up react-router-dom by running "npm install react-router-dom," but I am encountering unfamiliar errors that I am unsure how to resolve

PS C:\ReactP\sample> npm install react-router-dom npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afccc0ddca ...

Is it possible to shift the "ul" block of the navigation bar to the right without compromising the responsiveness toggle button functionality?

I'm currently using bootstrap NavBar and encountering an issue where moving the ul block to the right is disabling the toggle button responsiveness. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" c ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

The data list is failing to retain previous elements as new ones are incorporated

I have a list for uploads, and whenever I upload new data, the old data in the list gets removed. However, I want to display all the data together. How can I resolve this issue? const [fileList, setFileList] = useState<AddedFile[]>([]); const beg ...

Implementing custom validation in React to dynamically enable/disable buttons

I am working on a basic form that includes 3 input fields and one submit button. The submit button is initially disabled, and each input field has its own custom validation logic using regex. I am looking for a way to enable the button only when all the ...

Tips on adding an item to an array with React hooks and TypeScript

I'm a beginner with a simple question, so please bear with me. I'm trying to understand how to add an Object to the state array when a form is submitted. Thank you for your help! interface newList { name: string; } const ListAdder = () => { ...

The functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

I encountered an issue while trying to generate a React app with npx

Struggling with setting up a React app on my Windows machine, looking for some assistance here. I've tried running the following command in Hyper Terminal: npx create-react-app new-app After checking that my Node.js version is 12.16.1 and both npm and ...

Steps to shorten HTML content while maintaining consistent column width

Is there a way to ensure that the fixed column width is maintained even with long strings? I am trying to display a report in a jsp by having headers in one table and content in another table, both with columns set to the same width. However, some of the ...

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...

Does Material-UI MenuItem pass arguments to the onClick handler function?

I am currently working with a search.js file and a search-date.js file. Within the search.js file, there is a container called SearchDate which I render. However, I'm puzzled by the behavior of the MenuItem component when it is clicked. The function ...

What is the process for incorporating a responsive range into a mui class?

Looking for a way to apply margin within the range of 565-350px in MUI4 using only one media query line. Any suggestions on how to achieve this? view: { display: 'flex', justifyContent: 'center', flexWrap: &apos ...