How can I display a blank date picker using Material UI in a REACT application?

CURRENT SETUP

<MuiPickersUtilsProvider utils={DateFnsUtils}>
     <DatePicker
      fullWidth
      value={dob}
      label="Date of Birth"
      format="dd / MM / yyyy"
      margin="normal"
      maxDate={new Date()}
      InputProps={{ className: css.datepicker }}
      ></DatePicker>
</MuiPickersUtilsProvider>

CSS Styling

.datepicker {
  margin: 2px 0px 2px 0px;
  height: 60px;
  width: fit-content;
  padding: 20px 15px 10px;
  border-bottom: 2px solid $lightGrey;
  background-color: #fff;
  color: #2c2c2c;
  width: 300px;
  font-weight: 600;
}

Behavior when field is empty

https://i.sstatic.net/QAaVV.png

Expected Behavior when field is empty

https://i.sstatic.net/Mf1nI.png

Can the Material UI date picker be styled to match the image provided?

Answer №1

  • To ensure the Date Picker works as expected, set the initial value of the date to null in your state.
  • You can also utilize the emptyLabel property to specify a custom placeholder text when the date is null.

View the demo on codesandbox here

code

function App() {
  const [dob, setDob] = useState(null); //<--- pass initial value as null
  const handleDateChange = date => {
    setDob(date);
  };

  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <DatePicker
        fullWidth
        onChange={handleDateChange}
        value={dob}
        label="Date of Birth"
        format="dd / MM / yyyy"
        margin="normal"
        maxDate={new Date()}
        emptyLabel="custom label" //<--- custom placeholder when date is null
        //  InputProps={{ className: css.datepicker }}
      />
    </MuiPickersUtilsProvider>
  );
}

Edit: responding to follow-up questions from comments.

  1. Hide the floating label when the date is null - Set the label value when dob has a value
label={dob && "Date of Birth"}
  1. Style the Empty label - Utilize makeStyles and InputProps
const useStyles = makeStyles(theme => ({
  datepicker: {
    margin: "2px 0px 2px 0px",
    height: "60px",
    // width: 'fit-content',
    padding: "20px 15px 10px",
    borderBottom: "2px solid blue",
    backgroundColor: "#fff",
    color: "#2c2c2c",
    width: 300,
    fontWeight: 600
  }
}));

function App() {
  const [dob, setDob] = useState(null); //<--- pass initial value as null
  const classes = useStyles();
  const handleDateChange = date => {
    setDob(date);
  };

  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <DatePicker
        fullWidth
        onChange={handleDateChange}
        value={dob}
        label={dob && "Date of Birth"}
        format="dd / MM / yyyy"
        margin="normal"
        maxDate={new Date()}
        emptyLabel="custom label" //<--- custom placeholder when date is null
        InputProps={{ className: !dob ? classes.datepicker : null }} //<----apply style when no date selected
      />
    </MuiPickersUtilsProvider>
  );
}

The codesandbox demo has been updated to incorporate all the modifications mentioned above.

Answer №2

Implementing this snippet of code will ensure that the MUI DatePicker does not show an error message when the date value is null or undefined:

<LocalizationProvider dateAdapter={AdapterDayjs}>
  <DatePicker
    value={selectedDate !== null ? dayjs(selectedDate) : null}
    onChange={(newDate) => setSelectedDate(newDate)}
  />
</LocalizationProvider>

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

Error message: "The term 'Outlet' is not recognized in react-router version 6.4"

What is the proper way to define the Outlet component in react-router version 6.4? Below is a code snippet: function Layout() { return ( <div> <Navbar /> <Outlet /> <Footer /> </div> ); } ...

What is the proper way to align text based on the text above using CSS?

I have a container with a width of 50% of the viewport width, which contains some text. I want to align some other text below it to the right side. You can find an example here: https://jsfiddle.net/hadr4ytt/1/ Here is the current CSS for this: .containe ...

Documenting React Native Components: Best Practices and Tips

How can I add comments to a React Component? import React, { useState } from 'react'; import { Text, TextInput, View } from 'react-native'; import PropTypes from "prop-types"; const PizzaTranslator = ({ pizzaEmoji = ' ...

Issue with Material-UI ThemeProvider failing to pass down themes to components

I've set a custom theme in my App.js that overrides the Primary and Secondary colors. I have wrapped a Home component with a ThemeProvider. However, the overridden values are not reflecting in the Home component. Can someone help me identify what I&ap ...

Building a Responsive Page with Bootstrap 4

I'm currently working on a design page with 2 boxes on the left side and 3 boxes on the right. It looks great on desktop, but I want the boxes to display individually on mobile devices and I'm having trouble figuring it out. Here is my code: < ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

What is the best way to incorporate Express following an asynchronous function?

After setting up my Firebase and initializing it, I managed to retrieve data from it. However, I encountered an issue when trying to use express.get() and json the data into the server. I'm unsure of what the problem could be. let initializeApp = requ ...

What's the reason behind the console showing an uncaught promise error message?

When attempting to delete some lists from my backend using a fetch request, I encountered an issue. The console is displaying an error message that reads "Uncaught (in promise)." What could be causing this problem? Here is the frontend code snippet for th ...

What is the best way to create a fixed contact form on specific pages?

There is a Contact Form 7 on the webpage that I want to make fixed to the right side. Initially, the form is hidden and only the form button (open) is visible. When clicked, the form should open. ...

How can I fix the error saying "prop-types not detected on request"?

I'm embarking on a fresh ReactJS project utilizing material-ui Next along with fuse-box. All necessary dependencies have been successfully installed: "dependencies": { "material-ui": "^1.0.0-beta.27", "material-ui-icons": "^1.0.0-beta.17", ...

Unable to invoke a custom hook within another custom hook in a React application

I've developed a React application using create-react-app. Currently, I'm working on creating a custom hook that integrates with the Microsoft Authentication Library (MSAL). MSAL provides a custom React hook that I want to utilize within my own ...

The setState method fails to properly update the state

I am currently utilizing React JS. Below is the code for my React class: class MyReactComponent extends React.Component{ constructor(props){ super(props); this.state = { passAccount: { email: "Email&quo ...

You may encounter the issue of receiving a message stating "Origin is not allowed by Access-Control-Allow-Origin" while utilizing Django authentication on a specific URL

I'm encountering CORS issues with Django and React (fetch). Here's how Django is configured: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "dja ...

Basic image slider featuring adjustable heights

I'm currently working on a basic content slider, but I've encountered an issue where the container doesn't expand as new content slides in. It seems to be related to the absolute positioning of the content items. If I don't use absolute ...

Define the input field as a specific type and disable the Material-UI text formatting

I am using a Texfield component from Material UI, but I have noticed that every time I type, the input stops and doesn't continue to the next letter. I have to click on it again in order to continue typing. When I remove the onChange method, the data ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

ReactJS encounters an issue with reading the property 'map' as undefined

I've gone through several top posts in my search, but none of them quite match my situation. Surprisingly, VSCode was able to recognize that function, yet React couldn't? Here's my jsx: (EDIT: Thanks to @Dannis Vash, it appears the sorting ...

Having trouble getting custom Themes to apply in Material UI version 5

I meticulously followed the documentation to create a custom theme, but unfortunately, I'm not seeing any changes reflected in my UI. Both the primary and secondary colors remain the same as the default, despite my efforts. Additionally, the warning, ...

What would be the best way to display a label once the zoom level exceeds a certain threshold in Leaflet?

As someone new to the Leaflet library and JavaScript in general, I'm currently facing a challenge with showing/hiding a leaflet label based on the zoom level. The markers are within a 'cluster' layer loaded via AJAX callback, and I bind the ...

CSS technique to display background on hover

My website has a bootstrap 'More' dropdown feature on the left navigation bar. However, there is an unwanted background hover effect that I can't seem to remove. Despite removing all background hovers from my CSS, the issue persists. Can any ...