Cannot Read Property 'href' of Undefined React-code-input Next

Got an fault like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to prepare this one specifically, and forth the way you'll learn how to arroyo 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 Fix

This error usually means yous're trying to apply .map on an array, but that assortment isn't divers yet.

That's frequently because the assortment is a piece of undefined country or an undefined prop.

Brand sure to initialize the land properly. That ways if it volition eventually be an array, employ useState([]) instead of something like useState() or useState(nada).

Let's look at how nosotros tin interpret an fault message and track down where it happened and why.

How to Observe the Error

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

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div central = {item . id} >
11 | {detail . proper noun}
12 | < / div >

Look for the file and the line number commencement.

Here, that'southward /src/App.js and line nine, taken from the light gray text in a higher place the code block.

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

How to Read the Stack Trace

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

These always await long and intimidating, simply the fox is that commonly yous tin can ignore most of information technology!

The lines are in order of execution, with the well-nigh 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:9)                                            at renderWithHooks (react-dom.evolution.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.evolution.js:2804)                              at beginWork              $1                              (react-dom.evolution.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.evolution.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.development.js:17672)                              at evaluate (index.js:seven)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (managing director.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              >                              [every bit 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 outset 2 lines are all we care most hither.

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

Allow's decode a couple of these lines:

Here nosotros take:

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

Let'south look at another i:

                          at performSyncWorkOnRoot (react-dom.development.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'southward a large file!)

Ignore Files That Aren't Yours

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

Usually, that means you'll pay attention to but the first few lines.

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

In that location are some cases where you lot do care almost the full stack, but they're few and far betwixt, in my feel. Things like… if yous suspect a issues in the library you're using, or if you lot think some erroneous input is making its way into library code and blowing up.

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

Follow the Clues: How to Diagnose the Error

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

Hither'southward the full text of that file:

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

Line 9 is this i:

And just for reference, here'southward that mistake bulletin over again:

                          TypeError: Cannot read holding 'map' of undefined                                    

Permit's interruption this downwardly!

  • TypeError is the kind of error

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

  • Cannot read holding means the code was trying to read a holding.

This is a skilful clue! 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 holding of the user object.

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

There's too brackets (aka foursquare brackets, []) for accessing items in an array, similar items[5] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – but remember, 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 office. It didn't go that far, because items is undefined.

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

This ane is another cracking inkling. Combined with the previous bit, you can be pretty sure you should be looking for .map somewhere on this line.

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

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

And so at present y'all can slice this all together:

  • find the line that the mistake occurred on (line 9, hither)
  • scan that line looking for .map
  • look at the variable/expression/any immediately before the .map and be very suspicious of information technology.

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

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

This defines the variable simply information technology doesn't ready information technology to annihilation, which means its value is undefined. In that location'due south the problem. Fix that, and you fix the error!

Fixing This in the Real Earth

Of course this example is tiny and contrived, with a simple mistake, and information technology's 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.

Mayhap items is a prop passed in from the parent component – and yous forgot to laissez passer it downwards.

Or maybe you did laissez passer that prop, just the value beingness passed in is really undefined or null.

If it'south a local land variable, possibly yous're initializing the state equally undefined – useState(), written like that with no arguments, will do exactly this!

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

Any the case, though, the process is the same: outset where the fault is and work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.logs or utilize the debugger to audit the intermediate values and figure out why it'due south undefined.

You lot'll go information technology fixed! Skillful luck :)

Success! Now check your electronic mail.

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

Pure React plant

Larn 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'due south 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 stop devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

smithwitimpat01.blogspot.com

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

0 Response to "Cannot Read Property 'href' of Undefined React-code-input Next"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel