Search code examples
arraysreactjsarrow-functions

List all items in an array in ReactJS


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"...?


Solution

  • 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>
    }