1

This is the file that I'm rendering in App.js:

ProductList.js

import React from 'react'

export default function ProductList() {

    var items = JSON.parse(localStorage.getItem("products")); //[foo: "4.43", bar: "3.25"]

    const listitems = () => {
        for( var p in items) {
            <p>{p}, {items[p]}</p>
        }
    }
    return (
        <div>
            {listitems}
        </div>
    );
}

This does not output anthing.

The question is: how do I list all the items in an array like "foo, 4.43"...?

  • 1
    `listitems` is a function that you didn't call and even if you call it, it won't render anything because it returns nothing. Use the `map()` method to render the items in the list – Yousaf May 10 '21 at 16:13

2 Answers2

1
return (
  {items.map((el) => (
    <p>{el}</p>
  )}
)
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
0

I guess there are a few issues with this code.

First, the products you are getting from localStorage is an array, so you won't be able to get the key:value pair of it.

You would be better off transforming the products into an object, like:

{
  foo: "4.43",
  bar: "3.25"
}

Then, one alternative is to get the keys by doing const productKeys = Object.keys(products). Then map through them and display the values as well:

const listItems = productKeys.map(key => <p>{key}: {products[key]}</p>)

return {
  <div>
    {listItems}
  </div>
}
yaiks
  • 576
  • 3
  • 13