Search code examples
reactjsmaterial-uimui-xmui-x-date-picker

Material UI: How to change DatePicker text and calendar icon color?


I am trying to change the MUI X DatePicker (with Material UI) date text and calendar icon color.
I tried to change it passing style to InputProps, but it worked only for removing border.
Rather than that, nothing changes, I tried to apply style to theme.tsx, but it also didn't help. Any help will be appreciated.

import * as React from "react";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import AdapterDateFns from "@mui/lab/AdapterDateFns";
import LocalizationProvider from "@mui/lab/LocalizationProvider";
import DesktopDatePicker from "@mui/lab/DesktopDatePicker";
import { makeStyles, createStyles } from "@material-ui/core";

const useStyles = makeStyles(() =>
  createStyles({
    noBorder: {
      outline: "none",
      border: "none",
      color: "#fff",
    },
  })
);

export default function DatePicker() {
  const [value, setValue] = React.useState<Date | null>();
  const classes = useStyles();

  const handleChange = (newvalue: Date | null) => {
    setValue(newvalue);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Stack spacing={2}>
        <DesktopDatePicker
          inputFormat="dd/MM/yyy"
          value={value}
          onChange={handleChange}
          renderInput={(params) => <TextField {...params} />}
          InputProps={{
            classes: { notchedOutline: classes.noBorder },
          }}
        />
      </Stack>
    </LocalizationProvider>
  );
}

Solution

  • 1st solution - using sx property

    You can set sx property to <TextField/> component in order to overwrite default style properties:

    const color = "#c44242";
    ...
    return (
           <DatePicker
              renderInput={(params) => {
                return (
                  <TextField
                    {...params}
                    sx={{
                      svg: { color },
                      input: { color },
                      label: { color }
                    }}
                  />
                );
              }}
              ...other props
            />
      )
    
    

    Setting colors with sx prop

    2nd solution - providing a custom theme

    You can also create a custom theme and overwrite colors inside it:

      const theme = createTheme({
        components: {
          MuiIconButton: {
            styleOverrides: {
              sizeMedium: {
                color
              }
            }
          },
          MuiOutlinedInput: {
            styleOverrides: {
              root: {
                color
              }
            }
          },
          MuiInputLabel: {
            styleOverrides: {
              root: {
                color
              }
            }
          }
        }
      });
    

    Then you wrap your component with ThemeProvdier.

    Overriding Theme Demo