Skip to content Skip to sidebar Skip to footer

Styled Components Typeerror: Cannot Read Property 'createelement' of Undefined

Got an fault like this in your React component?

Cannot read holding `map` of undefined

In this post we'll talk nearly how to fix this i specifically, and along the fashion you lot'll acquire how to approach fixing errors in general.

Nosotros'll encompass how to read a stack trace, how to interpret the text of the mistake, and ultimately how to set it.

The Quick Ready

This error commonly means you're trying to employ .map on an array, only that array isn't defined yet.

That'due south often considering the array is a slice of undefined state or an undefined prop.

Make certain to initialize the state properly. That means if it will eventually be an array, use useState([]) instead of something like useState() or useState(null).

Permit's look at how nosotros can interpret an fault bulletin and track down where information technology happened and why.

How to Find the Fault

First order of business organisation is to figure out where the fault is.

If y'all're using Create React App, information technology probably threw up a screen like this:

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          half-dozen |                                                      return                                      (                                
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {particular . id} >
11 | {item . proper name}
12 | < / div >

Look for the file and the line number first.

Here, that's /src/App.js and line nine, taken from the light greyness text above the code block.

btw, when you see something like /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If you're looking at the browser panel instead, yous'll need to read the stack trace to effigy out where the error was.

These always look long and intimidating, but the trick is that usually you can ignore almost of it!

The lines are in order of execution, with the about recent offset.

Here's the stack trace for this error, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.development.js:12143)                              at beginWork (react-dom.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.evolution.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.evolution.js:17211)                              at                            eval                              (react-dom.development.js:17610)                              at unbatchedUpdates (react-dom.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.return (react-dom.evolution.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at One thousand.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (manager.js:257)                              at compile.ts:717                              at fifty (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [equally next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you lot could ignore near of it! The first 2 lines are all we care about here.

The showtime line is the error message, and every line after that spells out the unwound stack of function calls that led to information technology.

Let's decode a couple of these lines:

Here we have:

  • App is the name of our component function
  • App.js is the file where it appears
  • 9 is the line of that file where the fault occurred

Let's look at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it's a large file!)

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state it explictly: when you're looking at a stack trace, you can almost always ignore whatever lines that refer to files that are outside your codebase, like ones from a library.

Commonly, that means you'll pay attention to only the first few lines.

Scan down the list until information technology starts to veer into file names you don't recognize.

There are some cases where yous exercise care about the full stack, but they're few and far between, in my experience. Things like… if you suspect a problems in the library y'all're using, or if you think some erroneous input is making its manner into library code and blowing upward.

The vast majority of the time, though, the problems will be in your own code ;)

Follow the Clues: How to Diagnose the Fault

And then the stack trace told usa where to look: line ix of App.js. Let'southward open up that up.

Here's the full text of that file:

                          import                                          "./styles.css"              ;              consign                                          default                                          office                                          App              ()                                          {                                          permit                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              detail              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

And just for reference, hither's that error message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's intermission this down!

  • TypeError is the kind of error

There are a handful of built-in mistake types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is not of a valid blazon." (this part is, IMO, the least useful function of the mistake message)

  • Cannot read property means the lawmaking was trying to read a belongings.

This is a adept clue! At that place are just a few ways to read properties in JavaScript.

The most common is probably the . operator.

As in user.name, to access the name property of the user object.

Or items.map, to access the map property of the items object.

In that location'due south besides brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read office `map` of undefined" – just think, the JS interpreter has no idea what nosotros meant that type to exist. It doesn't know it was supposed to be an assortment, or that map is a function. It didn't get that far, because items is undefined.

  • 'map' is the property the code was trying to read

This one is another great clue. Combined with the previous bit, y'all can be pretty sure you should be looking for .map somewhere on this line.

  • of undefined is a clue almost the value of the variable

It would be way more useful if the error could say "Cannot read holding `map` of items". Sadly information technology doesn't say that. It tells y'all the value of that variable instead.

So at present you lot can piece this all together:

  • observe the line that the mistake occurred on (line 9, here)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately earlier the .map and be very suspicious of information technology.

Once y'all know which variable to look at, you can read through the function looking for where it comes from, and whether it's initialized.

In our little example, the simply other occurrence of items is line 4:

This defines the variable but it doesn't set information technology to annihilation, which means its value is undefined. In that location'southward the trouble. Gear up that, and y'all fix the error!

Fixing This in the Real World

Of form this instance is tiny and contrived, with a uncomplicated mistake, and information technology's colocated very shut to the site of the error. These ones are the easiest to set!

In that location are a ton of potential causes for an fault like this, though.

Mayhap items is a prop passed in from the parent component – and yous forgot to pass it downward.

Or maybe you did laissez passer that prop, simply the value being passed in is really undefined or zip.

If it's a local state variable, maybe you're initializing the land every bit undefined – useState(), written like that with no arguments, volition practice exactly this!

If it's a prop coming from Redux, possibly your mapStateToProps is missing the value, or has a typo.

Whatever the case, though, the process is the same: offset where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or utilize the debugger to inspect the intermediate values and figure out why it's undefined.

Y'all'll get it fixed! Adept luck :)

Success! Now cheque your email.

Learning React can be a struggle — then many libraries and tools!
My communication? Ignore all of them :)
For a step-by-pace approach, bank check out my Pure React workshop.

Pure React plant

Learn to think in React

  • 90+ screencast lessons
  • Full transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Start learning Pure React at present

Dave Ceddia'southward Pure React is a work of enormous clarity and depth. Hats off. I'k a React trainer in London and would thoroughly recommend this to all forepart end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

weaverthatintopen.blogspot.com

Source: https://daveceddia.com/fix-react-errors/

Postar um comentário for "Styled Components Typeerror: Cannot Read Property 'createelement' of Undefined"