Cannot Read Property 'element' of Undefined Form

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to gear up this 1 specifically, and along the way you'll learn how to approach fixing errors in general.

We'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to fix it.

The Quick Gear up

This error normally means you're trying to apply .map on an array, but that array isn't defined nevertheless.

That's oftentimes because the array is a piece of undefined land or an undefined prop.

Make certain to initialize the land properly. That means if it will somewhen exist an assortment, utilize useState([]) instead of something like useState() or useState(null).

Let's expect at how we can interpret an mistake message and track down where information technology happened and why.

How to Observe the Error

Get-go gild of business organisation is to effigy out where the fault is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      render                                      (                                
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div fundamental = {detail . id} >
11 | {detail . name}
12 | < / div >

Look for the file and the line number start.

Hither, that's /src/App.js and line ix, taken from the light gray text above the code cake.

btw, when yous meet something like /src/App.js:nine:13, the style to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If y'all're looking at the browser console instead, y'all'll demand to read the stack trace to figure out where the mistake was.

These always look long and intimidating, but the play a joke on is that unremarkably you can ignore most of it!

The lines are in social club of execution, with the near contempo first.

Here'southward the stack trace for this error, with the but important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:nine)                                            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.development.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.development.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.development.js:17211)                              at                            eval                              (react-dom.development.js:17610)                              at unbatchedUpdates (react-dom.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at Grand.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.e.              <              computed              >                              [as adjacent] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said yous could ignore virtually of information technology! The first 2 lines are all we care about here.

The first line is the error bulletin, and every line after that spells out the unwound stack of function calls that led to it.

Let's decode a couple of these lines:

Hither nosotros accept:

  • 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'southward look at some other one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the proper 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 just I wanted to country it explictly: when y'all're looking at a stack trace, you can almost e'er ignore any lines that refer to files that are exterior your codebase, like ones from a library.

Normally, that ways yous'll pay attention to just the first few lines.

Scan downwardly the listing until it starts to veer into file names you lot don't recognize.

There are some cases where you do care most the full stack, merely they're few and far between, in my experience. Things similar… if y'all suspect a problems in the library you're using, or if you lot think some erroneous input is making its mode into library code and blowing upward.

The vast bulk of the time, though, the bug will be in your own code ;)

Follow the Clues: How to Diagnose the Error

And so the stack trace told us where to look: line ix of App.js. Let'south open up that upwards.

Hither'due south the total text of that file:

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

Line 9 is this one:

And but for reference, here's that mistake message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'due south break this down!

  • TypeError is the kind of error

In that location 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 to the lowest degree useful office of the error message)

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

This is a good inkling! There are only a few ways to read backdrop in JavaScript.

The about common is probably the . operator.

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

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

There'due south as well brackets (aka square brackets, []) for accessing items in an assortment, like items[five] or items['map'].

You lot might wonder why the mistake isn't more specific, like "Cannot read part `map` of undefined" – merely retrieve, the JS interpreter has no idea what we meant that blazon to be. It doesn't know information technology was supposed to be an array, or that map is a function. Information technology didn't go that far, because items is undefined.

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

This i is some other great clue. Combined with the previous bit, you can exist pretty sure y'all should exist looking for .map somewhere on this line.

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

Information technology would exist style more than useful if the error could say "Cannot read belongings `map` of items". Sadly information technology doesn't say that. Information technology tells you the value of that variable instead.

So at present you can piece this all together:

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

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

In our lilliputian example, the only other occurrence of items is line iv:

This defines the variable but it doesn't set it to annihilation, which means its value is undefined. At that place'southward the problem. Gear up that, and yous fix the error!

Fixing This in the Real World

Of course this example is tiny and contrived, with a elementary mistake, and it's colocated very close to the site of the mistake. These ones are the easiest to fix!

There are a ton of potential causes for an fault similar this, though.

Possibly items is a prop passed in from the parent component – and you forgot to laissez passer it down.

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

If information technology's a local country variable, maybe you're initializing the country equally undefined – useState(), written like that with no arguments, will exercise exactly this!

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

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

You'll get information technology fixed! Skilful luck :)

Success! Now cheque your electronic mail.

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

Pure React plant

Learn to remember in React

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

Offset learning Pure React now

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

Alan Lavender

Alan Lavender

@lavenderlens

whiteimstionste.blogspot.com

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

0 Response to "Cannot Read Property 'element' of Undefined Form"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel