Typeerror: Cannot Read Property 'height' of Undefined

Got an error like this in your React component?

Cannot read holding `map` of undefined

In this mail service we'll talk about how to fix this 1 specifically, and along the style you'll learn how to approach fixing errors in full general.

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

The Quick Ready

This error usually means y'all're trying to utilize .map on an array, merely that array isn't defined yet.

That's often considering the array is a piece of undefined state or an undefined prop.

Make sure to initialize the state properly. That means if it volition somewhen be an assortment, use useState([]) instead of something like useState() or useState(zippo).

Let's look at how we tin can interpret an fault bulletin and track downwards where it happened and why.

How to Find the Fault

First gild of business is to figure out where the error is.

If you lot're using Create React App, it probably threw upward a screen like this:

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
seven | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div key = {item . id} >
11 | {particular . name}
12 | < / div >

Look for the file and the line number first.

Here, that's /src/App.js and line nine, taken from the calorie-free gray text above the lawmaking cake.

btw, when yous see something similar /src/App.js:9:13, the style to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These ever look long and intimidating, only the trick is that usually y'all can ignore nigh of it!

The lines are in guild of execution, with the most contempo get-go.

Here'southward the stack trace for this mistake, with the just important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.evolution.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              $1                              (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.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.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.e.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore nigh of it! The first two lines are all we intendance about hither.

The kickoff line is the error bulletin, and every line afterwards that spells out the unwound stack of part calls that led to it.

Let's decode a couple of these lines:

Here we have:

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

Permit's wait at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper name of the function where this happened
  • react-dom.evolution.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 information technology explictly: when you're looking at a stack trace, you can virtually always ignore any lines that refer to files that are outside your codebase, like ones from a library.

Usually, that ways you'll pay attention to only the outset few lines.

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

There are some cases where you exercise intendance well-nigh the full stack, only they're few and far between, in my feel. Things like… if you suspect a bug in the library yous're using, or if you think some erroneous input is making its way into library code and blowing upwardly.

The vast majority of the time, though, the issues volition exist in your own code ;)

Follow the Clues: How to Diagnose the Mistake

So the stack trace told united states where to look: line ix of App.js. Let'south open that upwardly.

Here's the full text of that file:

                          import                                          "./styles.css"              ;              export                                          default                                          function                                          App              ()                                          {                                          permit                                          items              ;                                          render                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          cardinal              =              {              particular              .id              }              >                                          {              item              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line nine is this 1:

And but for reference, hither's that error bulletin again:

                          TypeError: Cannot read property 'map' of undefined                                    

Allow'southward break this down!

  • TypeError is the kind of error

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

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

This is a skilful clue! There are simply a few ways to read properties in JavaScript.

The about mutual is probably the . operator.

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

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

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

Y'all might wonder why the error isn't more than specific, like "Cannot read function `map` of undefined" – but think, the JS interpreter has no idea what we meant that type to be. Information technology doesn't know it was supposed to exist 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 one is another great clue. Combined with the previous bit, you can be pretty sure you should exist looking for .map somewhere on this line.

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

It would be mode more useful if the mistake could say "Cannot read property `map` of items". Sadly information technology doesn't say that. Information technology tells you the value of that variable instead.

Then now you can piece this all together:

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

Once you know which variable to await at, you lot can read through the office looking for where it comes from, and whether it's initialized.

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

This defines the variable but it doesn't ready it to anything, which means its value is undefined. In that location'southward the trouble. Fix that, and you fix the error!

Fixing This in the Existent World

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

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

Maybe items is a prop passed in from the parent component – and y'all forgot to pass information technology down.

Or maybe you did laissez passer that prop, but the value beingness passed in is actually undefined or aught.

If it'due south a local state variable, maybe y'all're initializing the state as undefined – useState(), written like that with no arguments, will practise exactly this!

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

Whatever the instance, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouthward or employ the debugger to inspect the intermediate values and effigy out why it'south undefined.

You'll get it stock-still! Practiced luck :)

Success! Now check your email.

Learning React tin be a struggle — and then many libraries and tools!
My communication? Ignore all of them :)
For a pace-by-stride arroyo, 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 now

Dave Ceddia's 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 cease devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavander

@lavenderlens

archibaldasaints.blogspot.com

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

0 Response to "Typeerror: Cannot Read Property 'height' of Undefined"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel