Home > Software engineering >  React module logs perfectly on console, but does not show on the page
React module logs perfectly on console, but does not show on the page

Time:11-03

I am having a strange problem with the code below.

After mapping the notes, {notes.map(note => { ...}); console.log({notes}) returns an array of four items. There are four items in the array. Similarly, console.log({note.title}) logs each item's title as a map method would. When we call {note.title} on the line before console.log({note.title}), nothing appears on the page!!! An example of the code is shown below in a summarized form. The code with the problem has been pushed to the GitHub. You can see it under the commit "MyNotes.js not rendering the data on-screen while it logs them perfectly on the console".

The dev-tool console logs this error

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check your code at MyNotes.js:31.

https://github.com/bdarab/notezipper-mern

{
  notes.map((note) => {
    <Card style={{ margin: 10 }}>
      <Card.Header style={{ display: 'flex' }}>
        <span
          style={{
            alignSelf: 'center',
            color: 'black',
            cursor: 'pointer',
            flex: 1,
            fontSize: 18,
            textDecoration: 'none',
          }}
        >
          {note.title} // Doesn’t work console.log(note); // Works perfectly
        </span>

        <div>
          <Button>Edit</Button>

          <Button className='mx-2' variant='danger'>
            {' '}
            Delete{' '}
          </Button>
        </div>
      </Card.Header>
    </Card>;
  });
}

The strange thing is that everything works when I console.log() them, but it doesn't appear on the page. I continued coding blindly. Now, I have methods of showing {note._id}, {note.category}, and {note.content}that work perfectly when I log them on the console. In real code, though, I get no results. Why? https://github.com/bdarab/notezipper-mern

CodePudding user response:

add a return statement.

return <Card style={{ margin: 10 }}>

CodePudding user response:

It's a functional component that has no idea when notes exists. You need to use the two hooks useEffect and useState to tell your component when the data exists.

https://sebhastian.com/react-usestate-useeffect-hooks/

  • Related