How to render list of mongo objects in React component


We have already learned how to create mongo objects and array of objects, I put links below in case you need them.

Suppose we have the following document with array of tags which is a collection MongoDB objects. Our task is that render the list in the component.

{
    
    "tags": [
        {
            "posts": [
                "5fef1f5087a69346300003a7"
            ],
            "_id": "5fef1f5187a69346300003a8",
            "tagName": "Test",
            "createdAt": "2021-01-01T13:10:41.799Z",
            "updatedAt": "2021-01-01T13:10:41.855Z",
            "__v": 1
        },
        {
            "posts": [
                "5fef1f5087a69346300003a7"
            ],
            "_id": "5fef1f5187a69346300003a9",
            "tagName": "VM",
            "createdAt": "2021-01-01T13:10:41.804Z",
            "updatedAt": "2021-01-01T13:10:41.896Z",
            "__v": 1
        },
        {
            "posts": [
                "5fef1f5087a69346300003a7",
                "5fef1f7287a69346300003af",
                "5ff12f993ddcac34903623cd"
            ],
            "_id": "5fef1f5187a69346300003aa",
            "tagName": "JS",
            "createdAt": "2021-01-01T13:10:41.810Z",
            "updatedAt": "2021-01-03T02:44:43.120Z",
            "__v": 3
        }
    ],
    "_id": "5fef1f5087a69346300003a7",
    "title": "Title post",
    "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
    "user": {        
        "_id": "5fe4ab1e69b8d525c44ec293",
        "name": "admin",
        "createdAt": "2020-12-24T14:52:14.364Z",
        "updatedAt": "2021-01-03T02:44:41.780Z",
        "__v": 108
    },
    "createdAt": "2021-01-01T13:10:40.468Z",
    "updatedAt": "2021-01-03T02:37:55.982Z",
    "__v": 11
}

How to access the list in React

It is best practice to store the list as separate state in a React component and not to access is directly as {post.tags.map(element=>().

Accessing the tags list using post.tags.map(element=>() cause Type and map error.

State

Add the state and from the API calls method ( I used the componetDidmount method) . I skipped the portion of component for simplicity

//contructor 
constructor(props) {
    super(props);

    this.state = {
      post: Object,
      tags: [],
      comments: [],
    };
  }

.....
.....
componentDidMount() {
    const { pid } = this.props.match.params;

    axios
      .get(`http://localhost:3005/post/${pid}`)
      .then((res) => {
        if (res.data) {
          this.setState({ post: res.data, tags: res.data.tags ,});
        }
      })
      .catch((error) => {
        console.log(error);
      });

       const id =`http://localhost:3005/comment/${pid}`
       
     axios
       .get(id)
       .then((response) => {        
         this.setState({comments:response.data})
       })
       .catch((e) => {
         console.log(e);
       });
  }

Rendering the List

We are ready to render the list inside <div> tags state using a the map with key.

{this.state.tags.map((element) => (
              <span
                className="badge badge-info m-1"
                key={element._id.toString()}
              >                
                {element.tagName}{" "}
              </span>
            ))}

we had successfully rendered the list of mongo objects.

Following React posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.