How to render mongo document in Reactjs


MongoDB documents are are similar to rows in a relational database and collection as Table .Following is our sample mongo document we want to render in our React front end.

{    
    "_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-01T13:12:59.084Z",
        "__v": 106
    },
    "createdAt": "2021-01-01T13:10:40.468Z",
    "updatedAt": "2021-01-01T13:10:41.907Z",
    "__v": 3
}

We need to get rendered the post in a React component . To do this we need to do the following

  • Make API call – fetching the post
  • Save the object to state
  • Type cast the object and render

For simplicity I skip the rest of the component code.

State and API Call

....
constructor(props) {
    super(props);

    this.state = {
      post: Object,
   
    };
  }
.....

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

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

render() {
    return (
      <div>
        <div className="card m-2 p-2">
          <h3>{this.state.post.title}</h3>
          <div>{this.state.post.content} </div>
                 
     </div>
        </div>
      </div>
    );

Our API call return a single post, a mongo document , Note that we initialized the post (parent document) with Object in the constructor.

The data returned by the response object ( post) is a React acceptable object, so we can render it directly without any pain .

In this tutorial you have learned

  • Read parameter list from URL in React
  • API call in React
  • Render mongo document

Following React post/project deserve your attention

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.