How to fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI?

Sometimes, we need to fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI.

In this article, we’ll look at how to fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI.

How to fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI?

To fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI, we should wrap our Material UI components with the MuiThemeProvider component.

For instance, we write:

import { TextField } from "material-ui";
import React from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";

export default function App() {
  return (
    <MuiThemeProvider>
      <div>
        <TextField
          onKeyPress={(e) => {
            if (e.key === "Enter") {
              console.log(e.target.value);
            }
          }}
        />
      </div>
    </MuiThemeProvider>
  );
}

to wrap the TextField with the MuiThemeProvider component.

This lets Material UI apply the styles provided by Material UI for the components inside the MuiThemeProvider component.

Conclusion

To fix the “TypeError: Cannot read property ‘prepareStyles’ of undefined” error when developing React apps with Material UI, we should wrap our Material UI components with the MuiThemeProvider component.