Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below:

https://i.stack.imgur.com/fHMbn.png

Unfortunately, I couldn't find much guidance in the documentation. If anyone knows whether this customization is feasible and how to implement it, your assistance would be greatly appreciated.

--- EDIT ---

Following suggestions, I have added a button intended to overlay the calendar. Here is the code snippet for the button :

const useStyles = makeStyles({
  paper: {
    outline: 'none',
    padding: '10px',
    position: 'absolute',
    left: '50%',
    top: '50%',
    WebkitTransform: 'translate(-50%, -50%)',
    transform: ' translate(-50%, -50%)',
    width: 'auto',
    backgroundColor: 'white',
    textAlign: 'center',
  },
  infoButtonShown: {
    display: 'inline-flex',
    position: 'absolute',
    left: '50%',
    top: '50%',
    WebkitTransform: 'translate(-50%, -50%)',
    transform: ' translate(-50%, -50%)',
    color: 'black',
  },
  infoButtonHidden: {
    display: 'none',
    position: 'absolute',
    left: '50%',
    top: '50%',
    WebkitTransform: 'translate(-50%, -50%)',
    transform: ' translate(-50%, -50%)',
    color: 'black',
  },
});

<IconButton
    className={ isInfoOpen ? classes.infoButtonShown : 
                             classes.infoButtonHidden
              }>
    <InfoIcon fontSize="small" />
</IconButton>

However, the button does not appear on top of the calendar as expected. I have experimented with different z-index values but have not succeeded. Any insights on how I can position it above the calendar?

--- EDIT 2 ---

Building upon Ibrahim's suggestion, I am attempting to create a customized toolbar using ToolbarComponent :

import { DatePickerToolbar } from '@material-ui/pickers/DatePicker/DatePickerToolbar';

ToolbarComponent={(props) => (
    <div>
        <DatePickerToolbar {...props} />
        <IconButton
            className={
                isInfoOpen
                    ? classes.infoButtonShown
                    : classes.infoButtonHidden
            }
        >
            <InfoIcon fontSize="small" />
        </IconButton>
    </div>
)}

However, this implementation results in an error :

× TypeError: Cannot read property 'trackMetric' of null

I am quite lost here, especially given the lack of documentation on DatePickerToolbar. I had to provide the full path to avoid errors regarding its location within the @material-ui/pickers package. Is there a suitable toolbar available that I can use for this purpose?

Answer №1

To customize the toolbar, simply swap out the default component with your own custom one containing the desired elements

ToolbarComponent

For more information, refer to the documentation

import { ToolbarComponentDefault } from '@material-ui/pickers'



 <DatePicker 
  ToolbarComponent={(props) => (<div><ToolbarComponentDefault {...props /><OtherComponent /></div>))
/>

Answer №2

It took some effort, but I managed to come up with a solution like this :

Utilizing the ToolBarComponent attribute

ToolbarComponent={(props) => (
                <div>
                  <CustomToolbar {...props} />
                  <IconButton
                    className={
                      isInfoOpen
                        ? classes.infoButtonShown
                        : classes.infoButtonHidden
                    }
                    onClick={() => setInfoModalOpen(true)}
                  >
                    <InfoIcon fontSize="small" />
                  </IconButton>
                </div>
              )}

Furthermore, I had to create a CustomToolBar component to override the default toolbar in order to customize the rendering of the date (specifically for the Hebrew version):

const CustomToolbar = function(props: any) {


  const { date, isLandscape, openView, setOpenView, title } = props;

  const handleChangeViewClick = (view: any) => (e: any) => {
    setOpenView(view);
  };

  const classes = useStyles();
  const daysToHebrew = [
    "יום א'",
    "יום ב'",
    "יום ג'",
    "יום ד'",
    "יום ה'",
    "יום ו'",
    'שבת',
  ];
  const monthToHebrew = [
    "ינו'",
    "פבר'",
    'מרץ',
    "אפר'",
    'מאי',
    'יוני',
    'יולי',
    "אוג'",
    "ספט'",
    "אוק'",
    "נוב'",
    "דצמ'",
  ];

  return (
    <PickerToolbar
      className={classes.toolbar}
      title={title}
      isLandscape={isLandscape}
    >
      <ToolbarButton
        className={classes.h6ToolBar}
        onClick={handleChangeViewClick('year')}
        variant="subtitle1"
        label={date.getFullYear().toString()}
        selected={openView === 'year'}
      />
      <ToolbarButton
        onClick={handleChangeViewClick('date')}
        variant="h4"
        selected={openView === 'date'}
        label={`${daysToHebrew[date.getDay()]}, ${
          monthToHebrew[date.getMonth()]
        } ${date.getDate()}`}
      />
    </PickerToolbar>
  );
};

I hope this explanation benefits those who are looking for similar outcomes.

Answer №3

Place the content beside the DatePicker element, aligning it directly over the DatePicker using CSS positioning.

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: Required package bootstrap-duallistbox@github:istvan-ujjmeszaros/bootstrap-duallistbox is not found

After running npm install to install packages, I encountered the following error : npm ERR! code ELOCKVERIFY npm ERR! Errors were found in your package-lock.json, run npm install to fix them. npm ERR! Missing: bootstrap-duallistbox@github:istvan-ujj ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Tips on creating a repeating background image with CSS for a sprite

I'm facing a challenge that I can't seem to solve - I need to set a sprite as the background for a container. The issue is that despite my efforts, I haven't been able to achieve this. I've searched extensively but couldn't find a ...

Automate the process of saving information to Google Sheets using Google AppScript

I have a Sheet named 'Automatic' where I've imported a set of data using IMPORTXML. My goal is to update this data list daily at the same time to create a database with various stock quotes over time. Is there a way to accomplish this usin ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

Is there a way to prevent a web page from refreshing automatically for a defined duration using programming techniques?

I am currently working on a specific mobile wireframe web page that includes a timer for users to answer a question after the web content body has loaded. There are two possible outcomes when answering the question: 1) If the user fails to answer in time, ...

In Next.js, the state variable remains constantly undefined when using both useReducer and useContext

Using the Context API in my Next.js project has been giving me trouble lately. Every time I try to retrieve a value from the state using the Context API, I keep getting an error stating that it is "undefined." Here is my AppReducer.js file: const initi ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

Enhancing the SVG font size through custom CSS styling

Working with an SVG element and utilizing CSS to adjust the font-size of the text within the SVG. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720"> <rect class="vBoxRect" width="1280" height="720" fill="none" stroke="red"& ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...

Implement the window.open functionality within a directive for optimal performance

I am attempting to activate the function $window.open(url, windowName, attributes); in my Angular application by using an ng-click event. I have created a directive and enclosed the window.open method within a trigger function that is connected to a butto ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

The :empty selector is failing to function properly in @media print queries

Currently, I am working in Twig on Symphony and have encountered an issue with an empty div that needs to be hidden in print mode. <div class="form-fields__list"> </div> Surprisingly, the :empty selector works perfectly fine on the screen, bu ...

Hover effect that smoothly transitions to a background image appearing

I want to achieve a smooth fadeIn effect for the background image of a div. Currently, I have a function that displays the background image when hovering over the relevant div, but the transition is too abrupt. I would like it to fade in and out instead of ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causi ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...