E.K.Garcia
E.K.Garcia

Reputation: 49

Functional component returns object Object in react

I want to output the values of a json object. On each fetch, the type of values change from string to null. That's why I have the for loop and the if statement. Each constant inside the loop outputs the correct value but after it is added to listItems each <li> just returns [object Object]. I tried using <li>${value} (${time})</li> but this outputs the tags <li> as a string value.

function ValuesList(props) {
  
    let listItems = '';
    for(let i=1; i<=15; i+=1){
        const value = props.myDrink[`strValue` + i]; *//json code is: strValue1, strValue2, ... strValue15, with some of null value.*
        const time = props.myDrink[`strTime` + i];
        if (typeof value === 'string'){
            listItems += <li>{value} ({time})</li>
        }
    }
   
    return (<ul>{listItems}</ul>)
};

I have done this in jQuery before but I need to make it work in react. Should I change the +=? If not, what line should I fix? This is part of my first react project. Please help, thank you :)

Upvotes: 0

Views: 7539

Answers (2)

Sean W
Sean W

Reputation: 6608

You should directly map your items. There is no need to do what you used to do in jQuery.

if your drinks prop is an array

return (
 <ul>
  {props.drinks(map(({value, time}, i)=>{
    if (typeof value === 'string'){
     return <li key={`item-${i}`}>{value} ({time})</li>
    }
  })
 </ul>
)

if your drinks props is an object

return (
 <ul>
  {Object.entires(props.drinks).map(({ value, time }, i) => {
    if (typeof value === "string") {
     return <li key={`item-${i}`}>{value} ({time})</li>;
    }
   })}
 </ul>
)

Upvotes: 1

samuei
samuei

Reputation: 2102

Rather than concatenating JSX values into an empty string, push them into an array (with a key attribute):

let listItems = [];
 for(let i=1; i<=15; i+=1){
        const value = props.myDrink[`strValue` + i]; 
        const time = props.myDrink[`strTime` + i];
        if (typeof value === 'string'){
            listItems.push(<li key={/* some unique key. Probably your value */}>{value} ({time})</li>);
        }
    }

Upvotes: 1

Related Questions