Sean
Sean

Reputation: 23

React JS trying to return a Div

I have a JavaScript object that is being passed in via props and I would like to iterate over them to create a new div using the name and the value. I've tried using a forEach but found out that it doesnt return anything

I'm passing in a JS Object

let example = {all: 1255, rentals: 396, pip: 236, pm: 375, substatusCV: 0}

I know this probably looks terrible but it's my first go :)

import React from "react";

function Navbar(props){
 
  return (
    <div>
      {
        props.resp.all > '' ? ( 
            Object.entries(props.resp).forEach(([name, value]) => {
            // I'm able to return the key / value here but forEach doesnt return a value 
            // so I'm unsure how to create and return the div
              console.log(`${name}: ${value}`)

              // <div > {name} ({value})</div>
            })
          )
          : 'Loading'
      }
    </div>
  )
}

export default Navbar;

Upvotes: 0

Views: 505

Answers (2)

Lalit Sharma
Lalit Sharma

Reputation: 374

Let me put this in formal answer format.

Here in your code you are using Object.entries.

Object.entries returns a array of key value pair seprated in an array. So for your object {all: 1255, rentals: 396, pip: 236, pm: 375, substatusCV: 0} you will receive an array [["all", 1255], ["rentals", 396], ["pip", 236], ["pm", 375], ["substatusCV", 0]].

so now you can use all the array functions on this array. So your code will became.

 import React from "react";


function Navbar(props){
 
    return (
        <div>
            
            {
                props.resp.all > ''? ( 

                    Object.entries(props.resp).map(([name, value], index) => {
                        return <div > {name} ({value})</div>
                    })    

                ) : 'Loading'
            }

        </div>
        )
}

export default Navbar;

Upvotes: 1

Special Character
Special Character

Reputation: 2359

You are close but need to use the map function instead of forEach as well as needing to return the div.

import React from "react";


function Navbar(props){
 
    return (
        <div>
            
            {
                props.resp.all > ''? ( 

                    Object.entries(props.resp).map(([name, value]) => {
                        //I'm able to return the key / value here but forEach doesnt return a value so I'm unsure how to create and return the div

                        console.log(`${name}: ${value}`)

                        return <div > {name} ({value})</div>
                       
                    })    

                )

                  : 'Loading'
            
            }

        </div>
        )
}

export default Navbar;

Upvotes: 0

Related Questions