Tips on personalizing the DateTimePicker component from Material-UI

I am currently working on customizing the DateTimePicker component provided by Material-UI. To access its documentation, please visit:

One challenge I have encountered is the lack of styling information in the documentation. My goal is to change the main color for all colored components within the picker. So far, my approach has involved utilizing the general theme documentation and attempting to alter the theme's style:

const theme = createMuiTheme({
  status: {
    danger: '#FF72B1',
  },
  dateTimePicker: {
    headerColor: '#FF72B1',
    selectColor: '#FF72B1',
  },
  datePicker: {
    selectColor: '#FF72B1',
    headerColor: '#FF72B1'
  }
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Routes />
    </ThemeProvider>
  )
}

Based on my understanding of the theme documentation, I have defined styles within variables but they are not taking effect. It appears that specifying styles directly in the component itself is required, which presents a challenging aspect.

In my attempt to modify the Material-UI DateTimePicker, here's how it looks:

function MaterialDateTimePicker() {
  const classes = useStyles()
  return (
    <Fragment>
      <DateTimePicker
        label={label}
        inputVariant="outlined"
        value={value}
        onChange={onChange}
        classes={{
          root: classes.root,
          checked: classes.checked,
        }}
      />
    </Fragment>
  );
}

To apply styling, I've used the following code:

const useStyles = makeStyles(theme => ({
  root: {
    color: '#FF72B1',
    backgroundColor: 'orange',
    '& > .MuiPickerDTToolbar-toolbar.MuiToolbar-root': {
      backgroundColor: 'green'
    }
  },
  checked: {},
}));

This strategy is based on research findings, documentation study, as well as insights from Stack Overflow responses like this one: How to change material UI select border and label

The process involves locating the relevant CSS classes associated with each component for customization, either through documentation or inspecting the DOM if details are missing.

However, I have encountered some questions along the way:

1) In my specific scenario, when applying the root class to the DateTimePicker, it only affects the input component level. The calendar view triggered by JavaScript is not a direct child of this component, posing difficulties in accessing it.

The previous syntax does not function reliably in this case:

root: {
    color: '#FF72B1',
    backgroundColor: 'orange',
    '& > .MuiPickerDTToolbar-toolbar.MuiToolbar-root': {
      backgroundColor: 'green'
    }
  },

since root targets the input rather than the popup calendar.

2) Is this method the most effective solution when dealing with this library? Most feedback and complaints on platforms like Stack Overflow echo similar challenges. Are there any alternate strategies available?

3) While exploring the @material-ui/pickers module in the node_modules directory, I was unable to locate the CSS file for direct modifications. This contrasts with libraries like react-dates, where CSS customization is straightforward. Can the CSS stylings be accessed and customized in a similar manner for Material-UI Pickers? Where can these files be found?

A demonstration of my attempts can be viewed via this sandbox environment:

https://codesandbox.io/s/inspiring-napier-zh4os

(Please note that while the utility library is installed correctly, it is not functional in this context. Locally, the picker functions appropriately, although styling remains a challenge)

Answer №1

Currently, I am tackling this issue by utilizing a ThemeProvider to partially override the existing styles. You have the flexibility to pass your theme through your component as shown below:

 <MuiPickersUtilsProvider locale={deLocale} utils={DateFnsUtils}>
  <Grid container justify="space-around">
    <ThemeProvider theme={defaultMaterialTheme}>
      <KeyboardDatePicker
        ...
      />
    </ThemeProvider>
  </Grid>
</MuiPickersUtilsProvider>

You can customize your theme similar to this example:

import { createMuiTheme } from '@material-ui/core'

const defaultMaterialTheme = createMuiTheme({
  overrides: {
    MuiPickersCalendarHeader: {
      switchHeader: {
        color: '#6A148E',
        textTransform: 'uppercase',
      },
      dayLabel: {
        textTransform: 'uppercase',
      },
    },
    MuiPickersDay: {
      day: {
        color: '#707070',
      },
      daySelected: {
        backgroundColor: '#6A148E',
        '&:hover': {
          backgroundColor: '#6A148E',
        },
      },
      current: {
        color: '#6A148E',
      },
    },
    MuiSvgIcon: {
      root: {
        fill: '#6A148E',
      },
    },
    MuiOutlinedInput: {
      root: {
        '&:hover': {
          border: '10px solid red !important', // struggling with this part :/
        },
      },
    },
   
  },
})

export default defaultMaterialTheme

I hope this solution helps.

Answer №2

One strategy to override webkit appearance is by simply cancelling it out. There are various methods that can be used to nullify specific webkit styles in order to implement your own customization. Give this a shot:

-webkit-appearance: none;

If you're coding in ReactJS, consider using inline styles like this: webkitAppearance: "none";

Don't forget to explore other -webkit-[] properties as well. These properties allow for more targeted styling of elements such as borders and colors.

I hope this information proves to be helpful towards achieving your desired results :)

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

React error message: "Cannot update state on a component that is not mounted" unless using the useEffect hook

(I am a beginner using Next.js + Styled Components and need help :)) I'm currently working on creating a "Netflix" style page, with unique catalog components. Each content item in the grid is a complex component named ContentItem.js that is repeated ...

What are the best practices for creating a contemporary website that functions effectively on IE7?

After creating several websites for my clients, I discovered that they are not functioning well in IE7. Unfortunately, there is still a small percentage of people using IE7. Can anyone suggest a super quick solution to fix this issue? Feel free to recomm ...

Using the device's width and height with material-ui

Currently, I am attempting to specify the width and height for only the (Iphone 7 Plus) within my project using withStyles. import { withStyles } from "@material-ui/core"; I have tested the following code: "@media (width: 414px) and (height ...

My website is experiencing issues loading data from mongoDB

I recently ventured into the world of web development and took on the challenge of creating an E-commerce website using MERN stack a few months ago. My first big project was a success initially, but now I am facing issues with loading product images, categ ...

Is there a way to change the orientation of the cards so that they move from left to right instead of

I am looking to have my cards displayed from left to right rather than vertically, but I'm struggling to achieve this. I have tried using the float: left property with no success. Below is an example of a single card in my layout. They all follow the ...

Render a React component in JSX based on the asynchronous function that returns a boolean value

I'm having trouble implementing an HTML element to dynamically render based on the result of an async/await function. Unfortunately, my attempts so far have not been successful. Let me show you the async function that is causing the issue: const che ...

Having difficulty refreshing the chosen value post-rendering

I'm facing an issue with autocomplete where the selected value does not refresh after being rendered. I have provided an example at : https://codesandbox.io/s/test-material-ui-autocomplete-700nh?fontsize=14&hidenavigation=1&theme=dark import ...

Prevent Border Around Images within a Child DIV

Currently, I am in the process of designing a Tumblr theme and facing the challenge of making my pages visually appealing. One particular issue that is causing me trouble is my desire to have images on individual pages bordered in green with a maximum wid ...

The integrated authentication system in Django isn't functioning properly when used with React

I am in the process of developing a django-react application, utilizing Django for rendering templates, Django REST framework for handling API endpoints, and React integrated with Django templates. I have incorporated 'rest_framework.authentication.Se ...

Non Rectangular Header with Bootstrap's Responsive Navbar

Currently, I'm in the process of developing a website and I've been pondering if it's feasible to design a bootstrap navbar with a uniquely shaped header as a background. I envision the header to resemble something like this: https://i.sst ...

Turn off automatic downloading of embedded frame content in Safari for iOS

I am encountering an issue with a modal that displays a PDF and offers two options - one to print and one to download. The download option uses a blob with content-type: application/octet-stream, while the print option utilizes a blob with content-type: a ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

"Recently, I included a function called 'test' in the code, but I encountered an error stating that it was not recognized as a function. Can someone provide assistance

Issue Detected A 'TypeError' has been thrown: ".goal_test".click is not defined as a function Feel free to collaborate on the code by clicking this link: Please note that my modified code is enclosed within asterisk symbols. ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

When I click on my Material UI avatar image, it seems to override the button I had in

Every time I try to create a basic category filter with images, I encounter a frustrating bug. After examining the console log, it seems that when I click on the button, my image is being clicked and behaving like an image. However, when I click around the ...

What is the best way to conceal the dt tag when the dd tag contains no value

Is there a way to hide the "Subject" if the "subject_title" field is empty? <dt class="col-sm-6 text-dark" >Subject</dt> <dd class="col-sm-6">{{$course_dtl->subject_title }}</dd> For example, I would li ...

One possible revision: "Displaying errors on specific fields based on the results received from the API endpoint, without the use

When my API endpoint returns a 400 Bad Request with Validation Errors from FluentValidation, I aim to display these errors on the corresponding fields for user clarity. using Ardalis.ApiEndpoints; using MediatR; using Microsoft.AspNetCore.Mvc; using Que ...

Position the table footer on the right side of the page

I am trying to format a table with footer items in HTML. I want the first footer item to be aligned left and the rest to be aligned right. Here is the desired layout: https://i.sstatic.net/ZRNEp.png table { width: 100% } <table class="price-list" ...

What is the best way to adjust the width of a button to match the size of its

Is there a way to make a button automatically adjust its width to the parent div it is nested in? . Below is the code (html structure) for reference: <div class="drp"> <button class="drp-btn" id="i-drp-btn">m/s</button> <div i ...