Skip to content Skip to sidebar Skip to footer

How To Format And Display JSON Data Using Array.map In Reactjs?

I am trying to display data which is stored as userList state variable. I am trying to map each object and display name and email parameter from each object but it does not display

Solution 1:

As per your model schema, your user object contains userName and not name, so you would write user.userName in your displayUsers method, Also a key param is helpful in performance optimisation and you should add a unique key on the element returned by the iterator

 displayUsers(){
        return this.state.userList.map( user => {
          return(
            <div className="item-card" key={user.id}>
               <div className="info">    
                    <div className="username">Username: {user.userName}</div>
               </div>
            <div className="del-wrap">
                <img src={require("../../images/cancel.svg")}/>
            </div>
            </div>
            );
        })
  } 

Solution 2:

You need to add a key to the root element of map object to be returned. `

displayUsers(){
    return this.state.userList.map( user => {
      return(
        <div key={user.name} className="item-card">
           <div className="info">    
                <div className="username">Username: {user.name}</div>
           </div>
        <div className="del-wrap">
            <img src={require("../../images/cancel.svg")}/>
        </div>
        </div>
        );
    })
  }

Solution 3:

Before I edited your title, this would be a handy shortcut to display formatted JSON data right in the document.

displayUsers = () => <pre>{JSON.stringify(this.state.userList, null, '  ')}</pre>

to only display userName and email, use a whitelist array like this

JSON.stringify(this.state.userList, ["userName", "email"], '  ')

You can read more about JSON.stringify(value[, replacer[, space]]) here.


Post a Comment for "How To Format And Display JSON Data Using Array.map In Reactjs?"