Type Error Cannot Read Property 'createelement' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to fix this one specifically, and forth the way you'll learn how to approach fixing errors in general.

Nosotros'll embrace how to read a stack trace, how to interpret the text of the error, and ultimately how to set up it.

The Quick Set

This error commonly ways you're trying to utilize .map on an array, simply that array isn't defined yet.

That's often because the assortment is a piece of undefined state or an undefined prop.

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

Let's wait at how we tin interpret an error message and rail down where it happened and why.

How to Find the Mistake

Kickoff society of business is to figure out where the error is.

If you're using Create React App, it probably threw upwardly a screen similar this:

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          vi |                                                      return                                      (                                
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
x | < div key = {detail . id} >
11 | {item . name}
12 | < / div >

Wait for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the light gray text higher up the code block.

btw, when y'all see something like /src/App.js:9:xiii, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These always look long and intimidating, but the pull a fast one on is that usually you can ignore nigh of information technology!

The lines are in order of execution, with the most contempo first.

Here'south the stack trace for this error, with the merely of import lines highlighted:

                                          TypeError: Cannot                                read                                  property                                '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.evolution.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.evolution.js:2804)                              at beginWork              $ane                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.development.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.evolution.js:14770)                              at updateContainer (react-dom.development.js:17211)                              at                            eval                              (react-dom.evolution.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.due east.              <              computed              >                              [as side by side] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore about of information technology! The showtime 2 lines are all nosotros care virtually hither.

The start line is the error message, and every line later on that spells out the unwound stack of function calls that led to it.

Let'southward decode a couple of these lines:

Here nosotros have:

  • App is the name of our component part
  • App.js is the file where information technology appears
  • nine is the line of that file where the error occurred

Allow'due south expect at another one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'due south a big file!)

Ignore Files That Aren't Yours

I already mentioned this simply I wanted to state it explictly: when y'all're looking at a stack trace, you tin near ever ignore whatever lines that refer to files that are outside your codebase, like ones from a library.

Usually, that ways yous'll pay attention to only the first few lines.

Browse downwards the list until it starts to veer into file names you don't recognize.

There are some cases where you lot do intendance about the full stack, but they're few and far between, in my feel. Things like… if you suspect a bug in the library you're using, or if you recall some erroneous input is making its mode into library code and blowing upwardly.

The vast majority of the fourth dimension, though, the bug will be in your own code ;)

Follow the Clues: How to Diagnose the Mistake

So the stack trace told u.s.a. where to look: line 9 of App.js. Let's open that up.

Here's the total text of that file:

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

Line 9 is this 1:

And just for reference, here's that error bulletin again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of error

There are a handful of born error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful role of the error bulletin)

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

This is a good clue! In that location are simply a few ways to read properties in JavaScript.

The most common is probably the . operator.

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

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

There's also brackets (aka square brackets, []) for accessing items in an assortment, similar items[5] or items['map'].

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

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

This i is another bang-up clue. Combined with the previous bit, you lot can exist pretty certain you should exist 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 property `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.

And so now you lot tin can piece this all together:

  • find the line that the error occurred on (line 9, here)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately before the .map and be very suspicious of it.

Once you know which variable to look at, you can read through the function looking for where information technology comes from, and whether information technology'south initialized.

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

This defines the variable but information technology doesn't set it to anything, which means its value is undefined. At that place's the problem. Fix that, and y'all prepare the error!

Fixing This in the Real Earth

Of course this example is tiny and contrived, with a uncomplicated mistake, and it'southward colocated very shut to the site of the error. These ones are the easiest to fix!

There are a ton of potential causes for an error like this, though.

Peradventure items is a prop passed in from the parent component – and yous forgot to pass information technology down.

Or perchance you lot did pass that prop, but the value being passed in is actually undefined or null.

If it'south a local state variable, maybe you're initializing the country equally undefined – useState(), written like that with no arguments, volition exercise exactly this!

If information technology'due south a prop coming from Redux, perhaps your mapStateToProps is missing the value, or has a typo.

Whatsoever the case, though, the process is the aforementioned: start where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some panel.logsouth or use the debugger to inspect the intermediate values and effigy out why information technology'south undefined.

You'll go it fixed! Good luck :)

Success! Now check your email.

Learning React can exist a struggle — and then many libraries and tools!
My advice? Ignore all of them :)
For a step-past-step arroyo, check out my Pure React workshop.

Pure React plant

Larn to think in React

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

Start learning Pure React now

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

Alan Lavender

Alan Lavender

@lavenderlens

palmoresaws1972.blogspot.com

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

0 Response to "Type Error Cannot Read Property 'createelement' of Undefined"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel