banner



React-sketch Cannot Read Property 'offsetwidth' of Null

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to fix this one specifically, and along the manner you'll acquire how to approach fixing errors in full general.

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

The Quick Fix

This error unremarkably means you're trying to utilise .map on an array, just that assortment isn't defined yet.

That'south often because the array is a piece of undefined country or an undefined prop.

Brand sure to initialize the land properly. That means if it will somewhen be an assortment, use useState([]) instead of something like useState() or useState(null).

Let's look at how nosotros can interpret an fault bulletin and rail down where it happened and why.

How to Observe the Error

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

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

TypeError

Cannot read belongings 'map' of undefined

App

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

Wait for the file and the line number starting time.

Here, that's /src/App.js and line 9, taken from the light gray text above the lawmaking cake.

btw, when you meet 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 console instead, you'll need to read the stack trace to figure out where the error was.

These always look long and intimidating, but the flim-flam is that usually y'all can ignore well-nigh of it!

The lines are in lodge of execution, with the most recent first.

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

                                          TypeError: Cannot                                read                                  property                                '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.evolution.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              $one                              (react-dom.evolution.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.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 adjacent] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              at i (asyncToGenerator.js:25)                      

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

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

Permit's decode a couple of these lines:

Here we take:

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

Let's look at another ane:

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

Ignore Files That Aren't Yours

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

Commonly, that ways you'll pay attention to simply the commencement few lines.

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

There are some cases where you practice care virtually the full stack, merely they're few and far between, in my experience. Things like… if you doubtable a bug in the library yous're using, or if you lot think some erroneous input is making its way into library lawmaking and blowing upward.

The vast majority of the time, though, the bug volition be in your ain lawmaking ;)

Follow the Clues: How to Diagnose the Error

So the stack trace told us 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              ()                                          {                                          let                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              detail                                          =>                                          (                                          <              div                                          key              =              {              particular              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

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

                          TypeError: Cannot read belongings 'map' of undefined                                    

Let's suspension this down!

  • TypeError is the kind of mistake

At that place are a handful of congenital-in mistake 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 message)

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

This is a skilful inkling! At that place are only a few ways to read properties in JavaScript.

The most common is probably the . operator.

Every bit in user.name, to access the name property of the user object.

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

There's as well 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 than specific, similar "Cannot read office `map` of undefined" – but recall, the JS interpreter has no idea what we meant that type to be. It doesn't know information technology was supposed to be an array, or that map is a part. It didn't go that far, considering items is undefined.

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

This one is another great inkling. Combined with the previous scrap, y'all can be pretty certain you should exist looking for .map somewhere on this line.

  • of undefined is a clue well-nigh the value of the variable

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

So at present you can slice this all together:

  • notice the line that the fault occurred on (line 9, hither)
  • browse that line looking for .map
  • look at the variable/expression/whatsoever immediately before the .map and be very suspicious of it.

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

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

This defines the variable merely information technology doesn't set it to anything, which ways its value is undefined. There's the problem. Fix that, and you lot fix the error!

Fixing This in the Real World

Of course this example is tiny and contrived, with a uncomplicated mistake, and information technology'south colocated very close to the site of the fault. These ones are the easiest to fix!

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

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

Or possibly you did pass that prop, but the value being passed in is actually undefined or zero.

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

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

Whatever the case, though, the process is the same: get-go where the error is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logsouthward or use the debugger to audit the intermediate values and figure out why it's undefined.

You lot'll become it fixed! Skillful luck :)

Success! At present cheque your email.

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

Pure React plant

Learn to think in React

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

First 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 devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

reidthroaked.blogspot.com

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

0 Response to "React-sketch Cannot Read Property 'offsetwidth' of Null"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel