Customizing MaterialUI styles in React: A step-by-step guide

When utilizing Material UI with React, I am facing difficulty styling the Outline Select component according to my preferences. How can I override the default styles effectively?

Even after using withStyles, I am unable to achieve the desired appearance and functionality. For instance, modifying the border using a custom input within the Select element results in issues with the Label not behaving as expected; the border and label intersect instead of the label floating.

import { createStyles, makeStyles, withStyles } from '@material-ui/core/styles';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';

export const StyledSelect = ({ name, value, onChange, items }) => {
  const classes = useStyles();
  const inputLabel = React.useRef<HTMLLabelElement>(null);
  const [labelWidth, setLabelWidth] = React.useState(0);

  React.useEffect(() => {
    setLabelWidth(inputLabel.current!.offsetWidth);
  }, []);
  return (
    <FormControl variant="outlined" />
      <InputLabel
        ref={inputLabel}
        htmlFor={name}
      >
        {name}
      </InputLabel>
      <Select
        value={value || ''}
        onChange={onChange}
        input={<CustomInput labelWidth={labelWidth} />}
      >
        {items.map(item => {
          return (
            <MenuItem key={item.key} value={item}>
              {item.label}
            </MenuItem>
          );
        })}
      </Select>
    </FormControl>
  );
};


const CustomInput = withStyles(theme => ({
  root: {
    'label + &': {
      /* marginTop: theme.spacing(3), */
    },
  },
  /* label: {
    width: '',
  }, */
  input: {
    'borderRadius': 4,
    'position': 'relative',
    /* 'backgroundColor': theme.palette.background.paper, */
    'border': '2px solid #ced4da',
    /* 'fontSize': 16, */
    /* 'transition': theme.transitions.create(['border-color', 'box-shadow']), */
    // Use the system font instead of the default Roboto font.
    'fontFamily': [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
    '&:hover': {
      border: '2px solid red',
      borderRadius: 4,
    },
    '&:focus': {
      border: '2px solid #ced4da',
      borderRadius: 4,
      borderRadius: 4,
      borderColor: "#80bdff",
      boxShadow: "0 0 0 0.2rem rgba(0,123,255,.25)"
    },
  },
}))(OutlinedInput);

I aim to customize only specific elements without compromising the functionality of the Outline Select component.

Answer №1

When you interact with an input field in material UI, the class names change and a different style is applied to the label field.

Specifically, the class .MuiInputLabel-shrink gets added to the label element. To customize this styling, make sure to refer to this class in your withStyles()

For more information on the input-label API, visit: https://material-ui.com/api/input-label/#main-content

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 steps should I take to adjust the CSS code to properly integrate with my HTML file?

There seems to be an issue with the code provided. The CSS for the menu bar is not functioning properly with the HTML. <!DOCTYPE html> <html> <body class="news"> <head> <style type="text/css">body { margin: 0; paddi ...

Whenever I refresh my website after deployment, I encounter an empty error using the MERN stack

Here is a question I previously posted: How can I properly use the res.sendFile for my MERN APP, as I encounter an error every time I refresh, and it was resolved there. I encountered a similar issue here, even after following the same steps that worked b ...

Issues with material-ui login mutation experiencing inconsistency

Struggling to develop a sample login form in React using material-ui with graphql mutation. The login form is not functioning as anticipated. I can successfully log in at times, however, I am not seeing any data passed via loginMutation props in the conso ...

Utilizing a single component for various purposes with diverse tags in react

I am faced with the challenge of creating two almost identical components, Component A: const ClaimedLabel = ():React.Element => ( <div tw=""> <p tw="">Some Text here</p> <div tw=""> <Icon ...

Complications arising from IE when using strict doctype with CSS and jQuery

Here's the code I'm using for a sliding caption effect on my gallery site: I specifically implemented the last effect which is the Caption Sliding (Partially Hidden to Visible). $('.boxgrid.caption').hover(function(){ $(".cover", th ...

What steps can I take to prevent duplicate installations of React when releasing packages?

After working with React for quite a while, I recently delved into publishing packages. However, a dilemma has arisen regarding a dependency in the package I'm currently developing - conflicting React installations between the package and the project ...

I'm looking to enhance my redux state by implementing filters for a more precise control over the data. Where should I place the

I have this extensive object stored in my redux-store and I'm looking to streamline it into an array with specific keys. Should I implement the filter logic within the mapStateToProps method? Typically, my approach looks something like this: const m ...

Tips for customizing the localization of MUI(v5) date picker input or adding a placeholder text

Currently, I am working with a MUI5 DesktopDatePicker component that is detailed in the documentation found here. One issue I have encountered is that when I clear the selected date, the placeholder reverts back to dd/mm/yyyy, which is the default input f ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

Formatting an HTML table for mobile devices

Hi everyone, I'm struggling to understand why my table is displaying incorrectly when switching to the mobile version. I've attempted various CSS adjustments to correct it, but the issue persists when viewed on mobile devices. Mobile view of the ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

What methods can be used to create data for the child component?

Below is the primary code: import {Col,Container,Row} from 'react-bootstrap'; import {useEffect,useState} from "react"; import AppConfig from '../../utils/AppConfig'; import BB from './BB'; import React from "re ...

Angular does not adhere to globally defined styles

I have defined the margins for mat-expansion-panel in my styles.css file as follows: mat-expansion-panel { margin: 2vh; } Unfortunately, these margins will not be applied to my components unless they are also specified in the local CSS file. Even try ...

Creating a stylish navigation bar with custom components using Material UI and React

I've been experimenting with the BottomNavigation component from Material UI, but instead of using labels and text, I want to incorporate custom-made ImageButton components. Here's the code snippet from Material UI: import React from 'rea ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Component in NextJS

Is there a way to automatically refresh a remote JSON every 30 seconds in NextJS? I had it working smoothly in ReactJS, but after migrating to NextJS, errors started popping up. The issue seems to be related to certain elements that work fine in my ReactJ ...

The initial attempt to run the React npm start build was unsuccessful

While setting up a new React app, I encountered an issue where React fails to compile when running npm start for the first time after using npx create-react-app command. I haven't made any changes to the files and there are no additional packages in t ...

Is it possible to integrate a standalone MERN app into an existing website for hosting and deployment?

(I seem to be facing a challenge due to my lack of familiarity with available tools, as my searches haven't yielded much information on this topic.) Imagine I have a MERN project named my-app. When I run the server locally, it functions perfectly - I ...

Display additional information upon hovering without disrupting the neighboring elements

When I hover over a component, I want to display more details and scale it up. However, this action ends up displacing the surrounding components. Take a look at the screenshot for reference: Below is the code snippet where I defined the styling for an MU ...