robertszafa / moodportfolio

2 stars 1 forks source link

NodeViewer Looping JSX (Need Help on this one) #32

Closed DevGareth closed 5 years ago

DevGareth commented 5 years ago

For the NodeViewer I need to loop through and create the cards for the carousel/marquee. I can't because React sucks.

Any of you know how to do it?

I've tried a ton of different things at this point but nothing's worked.

thedata in render() of NodeViewer.js has the necessary data; the rest of render() can be changed as much as you want to try and make it work.

DevGareth commented 5 years ago

In more detail:

There is a function CarouselCard that returns the code for creating a card (a container with a photo's details). Inside nodeviewer is a function renderCard() that calls that.

You can run renderCard() repeatedly with no issues by copying and pasting it. However, I can't loop through them because render() doesn't allow regular loops inside of it.

So we need some way of looping through them, I think normally map is used somehow but I'm not sure.

DevGareth commented 5 years ago

Example of one apparent solution: https://flaviocopes.com/react-how-to-loop/

And another with objects: https://stackoverflow.com/questions/22876978/loop-inside-react-jsx

I've tried to implement that kind of thing can't do it though.

rahul-kothari commented 5 years ago

It breaks because you are missing the key attribute in div.

In render() line 70-90:

var cardList = [];

for (var i = 0; i < thedata.length; i++) {
    cardList.push(
        <div key={i} className="card">
            <CarouselCard timestamp = {thedata[i].state.timestamp} imgUri = {thedata[i].state.photoUri} emotion = {thedata[i].state.dominantEmotion} key={i}/>
        </div>
    )

  return cardList;
}

In React16 you should be able to return the array directly. refer 3rd most voted answer on https://stackoverflow.com/questions/32157286/rendering-react-components-from-array-of-objects

DevGareth commented 5 years ago

Think that works, data not working quite right so will need to fix that to check. Also, just so I remember, return should be outside of for.

robertszafa commented 5 years ago

You can also have a look at RecentPhotos and TagMenu where the parent also creates Photo and Tag respectively by looping through an array.

Both approaches need a key in the top level HTML/Component tag

DevGareth commented 5 years ago

Have implemented this solution to NodeViewer but it still doesn't work.

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {neutral}). If you meant to render a collection of children, use an array instead.

DevGareth commented 5 years ago

Solved. Was caused by dominant emotion being stored in key format.