Cannot read properties of undefined (reading ‘main’) – Solution
This post contain affiliate links to Udemy courses, meaning when you click the links and make a purchase, I receive a small commission. I only recommend courses that I believe support the content, and it helps maintain the site.
I was recently upgrading a React app to all newer packages. This was a pretty long and intensive job, and I ran into a number of issues.
One issue that popped up and I really struggled with was the following:
TypeError: Cannot read properties of undefined (reading ‘main’)
This error was only showing when running Jest tests. The project used React Testing Library and the error was highlighted to be coming from the render
function.
What Causes The Error
Turns out I had missed an item when migrating Material UI from V4 to V5.
Material UI introduced a number of breaking changes when moving from V4 to V5. A lot of great fixes were added, as well as feature updated.
One of these changes was how the <button />
component uses the color
prop.
The button color
prop is now primary
by default, and default
has been removed. This makes the button closer to the Material Design guidelines and simplifies the API.
How To Remove the Error
There are a couple of ways to handle this issue.
The first is to remove default
from the color
prop and allow the button to return to its primary
color. This isn’t particularly helpful if you are needing to show the difference between buttons.
Another way to to replicate the default
state. Rather than passing color="default"
, you can change default
to grey
. Then following this example, add the original default styling.
Hopefully this has helped, if you as stuck as I was!