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

How to place custom route links in Reactjs component


Suppose you have a React application which uses link to navigate another route/page. How do we place the link ? . Let’s look at the post example.

const PostTitles= props=>(
  <div>
    <div>Date: {props.post.createdAt} </div>    
    <a href=`/post/${props.post._id}` >{props.post.title} </a>
  </div>
)

In the above code is a part of blogging web app, which consists of posts,uers,comments and tags components. In PostTitles component which shows title link of posts we used back tick ( `) to add variable. The back tick inside the render part may not work perfectly as in JavaScript.

Solution

So to make it work we have to add pair of extra curly braces ({}) as follows

const PostTitles= props=>(
  <div>
    <div>Date: {props.post.createdAt} </div>    
    <a href={`/post/${props.post._id}`} >{props.post.title} </a>
  </div>
)

Following React posts may help you