How to remove the label from mui/x-date-pickers/DatePicker and retain the top border?

Viewed 27

I have created a Date component, which renders a mui/x-date-pickers/DatePicker object. Note the component is wrapped in a react-hook-form Controller. Since the datePicker will display in a form, I want all components to display with the label above the component. However, when the datepicker has a value, it adds a label to my DatePicker, by removing a portion of the DatePicker's top border. If I remove the label, the top border is also removed. However, if the datePicker has no value selected, the label becomes placeholder text(see screenshots below). I would like the ability to remove the label, without it effecting the datePicker's border. I created the component by referencing the basic example Basic Example (see Basic Code Example). Is there any way to remove the label and retain the border, when the datePicker has a date value selected, so I can add a label above the datePicker myself?

DatePicker with Default Value with Label:

enter image description here

DatePicker with default Value without Label:

enter image description here

DatePicker without default Value with Label as Placeholder

enter image description here

Code Snippet:

import React from "react";
import {LocalizationProvider} from "@mui/x-date-pickers";
import {AdapterMoment} from "@mui/x-date-pickers/AdapterMoment";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import {TextField} from "@mui/material";
import {Controller} from "react-hook-form";
import "./style.css";

const DateSelector = ({ name, label, control }) => {
  const [value, setValue] = React.useState(new Date());

  function handleDateChange(date, field) {
    // console.log("handleDateChange: Data:", data);
    setValue(date);
    field.onChange(date);
  }

  return (
    <div className="form-group">
      <Controller
        name={name}
        control={control}
        defaultValue={value}
        render={({ field, ...props }) => (
          <LocalizationProvider dateAdapter={AdapterMoment}>
            <DatePicker
              name={name}
              inputFormat="MM/DD/YYYY"
              label={label}
              value={value}
              onChange={(date) => handleDateChange(date, field)}
              renderInput={(params) => {
                // console.log("Params:", params);
                return <TextField {...params} />;
              }}
            />
          </LocalizationProvider>
        )}
      />
    </div>
  );
};

export default DateSelector;
0 Answers
Related