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(){
returnthis.state.userList.map( user => {
return(
<divclassName="item-card"key={user.id}><divclassName="info"><divclassName="username">Username: {user.userName}</div></div><divclassName="del-wrap"><imgsrc={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(){
returnthis.state.userList.map( user => {
return(
<divkey={user.name}className="item-card"><divclassName="info"><divclassName="username">Username: {user.name}</div></div><divclassName="del-wrap"><imgsrc={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?"