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 :)
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>);
}
}