How to solve this error Can not find utils in context
If you are using IntelliJ IDEA 2020.2.3, then the following could help.
In my case, it was one of those stupid mistakes you can spend an hour or two to hunt down. So I copied and pasted the example from the official docs. I copied the component <MuiThemeProvider/>
and then used the autocorrection feature of IntelliJ i.e Alt+Ener
. So far, so good, see the screen:
I chose the first line as it seems that IDE correctly suggested the autocorrection. It inserts the following import at the header of the file:
import MuiPickersUtilsProvider from "@material-ui/pickers/MuiPickersUtilsProvider";
And it turns out that it's an incorrect version of using import for MuiThemeProvider
. The correct version is:
import {MuiPickersUtilsProvider} from "@material-ui/pickers";
Be careful about using the autocomplete feature. Most of the time, it's working as you expect but not always, unfortunately. In this particular case, it's just better to ensure that all imports from the official example are the same as in your code.
Try wrapping it (like in the example: https://material-ui.com/components/pickers/):
import React, { Fragment, useState } from "react";
import DateFnsUtils from '@date-io/date-fns';
import { DateTimePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
function BasicDateTimePicker() {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DateTimePicker
label="DateTimePicker"
inputVariant="outlined"
value={selectedDate}
onChange={handleDateChange}
/>
<DateTimePicker
autoOk
ampm={false}
disableFuture
value={selectedDate}
onChange={handleDateChange}
label="24h clock"
/>
<DateTimePicker
value={selectedDate}
disablePast
onChange={handleDateChange}
label="With Today Button"
showTodayButton
/>
</MuiPickersUtilsProvider>
);
}
export default BasicDateTimePicker;
I tried to solve the problem quite long. I forgot to wrap the DatePicker
component with <LocalizationProvider dateAdapter={AdapterDateFns}>.
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DatePicker from '@mui/lab/DatePicker';
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
disableFuture
label="Responsive"
openTo="year"
views={['year', 'month', 'day']}
value={dateValue}
onChange={(newValue) => {
setDateValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
The above solution worked for me