Home > Software engineering >  React Component inside .map() is throwing an error: TypeError: notes.map is not a function
React Component inside .map() is throwing an error: TypeError: notes.map is not a function

Time:10-27

am trying to show Noteitem component which is returned inside a map function.

        {notes.map((note) => {
          return (
            <Noteitem key={note._id} updateNote={updateNote} showAlert={props.showAlert} note={note} />
          );
        })}

CodePudding user response:

notes should be an array for map function to work. You can check it in following way if notes is not null and is an array using notes.length and apply map function

{notes && notes.length && notes.map((note) => {
          return (
            <Noteitem key={note._id} updateNote={updateNote} showAlert={props.showAlert} note={note} />
          );
        })}

CodePudding user response:

You can put if/else statement inside JSX to check the variable whether is exist or not

return (
   <>
      {
        notes.length
           ? 'fallback'
           : notes.map(note => <Noteitem key={note._id} updateNote={updateNote} showAlert={props.showAlert} note={note} />)
      }
   </>
)

IIFE

{(() => {
   if ("check note") {
      // fallback
   }
   return notes.map((note: NoteProps) => (
      <Noteitem key={note._id} updateNote={updateNote} showAlert={props.showAlert} note={note} />
   ));
})()}
  • Related