How to clear all element in mongoose object array in Nodejs


Mongoose array can set of objects basically a reference to other mongoose document placed in other document. Our task is to clear all element stored in MongoDB array of objects.

To clear we can use pull or simply an assign a blank array ([]). In our Post example we had tags array.

post.tags=[]

[] will clear all of the tag id in the tags object array

Use dotenv to store configurations in Reactjs


A modern Reactjs app can be consisting of multiple components, connection to different databases, APIs etc. In other Nodejs projects we can use the dotenv package to store configuration details and can access with process.env.

Is dotenv useful for Reactjs ? Yeh.

Suppose you have using an API in many of the components and wanna some correction in API path, may be a change in basic URL. What we do ? Go through all of the component and change the base URL. Tiresome job !

For such case place the URL in .env (/src) file and use the process.env.REACT_APP_API_SERVER in all of the component. Yo need to change only the .env file for updating base URL.

First up all install the package using

npm i dotenv

and in the App.js , require the package as follows and use it in the component

....
require("dotenv").config();
 .get(`${process.env.REACT_APP_API_SERVER}/post/find`)
      .then((response) => {

        if (response.data.length > 0) {
          this.setState({
            posts: response.data,
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });

How to export multiple components in Reactjs


Usually we organize components React components in separate files. But for smaller components associated with component we are using need not be placed in operate file. In short it is possible to place multiple components in a single js file and export them.

 .....
  our component codes goes her

module.exports= {Post,Tags,Comments}

In the above fashion we can export the components and can import the components as follows

 const {Post,Tags,Comments} =from './components'

How to create ant row design for Reactjs


We are already learn how can utilize the antd for a Reactjs projects. Let’ quickly design a rows with columns ( a grid design) using the easy to use customize UI provided by Ant Design .

Go to Ant Row documentation , adjust the gutters and column count and click the copy code icon and past it where ever you need them.

Following ant design posts deserve good read

Ant layout for Reactjs apps


Ant Design is a UI Kit for developing beautiful web app and it is the second most popular one, it is just like Bootstrap we are familiar. In fact many apps have using multiple UI kits, there are plenty of UI kit available.

Install antd

Using Layouts we can create a skeleton structure of the app, which includes header, footer and content section. For using them in our React app, install the package using

npm i antd

Import Ant Design components

In our app.js we need to import the package extract the header,content,footer objects and also the css for beautify the objects as follows.

import { Layout} from "antd";
import "antd/dist/antd.css";
const { Header, Content, Footer } = Layout;

Create app layout

We have everything we needed, the Header,content,Footer components , Lets organize our app layout in app.js file of React app,

<Router>
<Layout className="layout" style={{ background: "##f759ab" }}>
      <Header>
        Your custom header components here
      </Header>
      <Content style={{ padding: "0 15px" }}>
      <Route path="/about" exact component={AboutUs} />
        You can place more routes/content here 

      </Content>
      <Footer style={{ textAlign: "center" }}>
        space for custom footer component
      </Footer>
    </Layout>
</Router>

That is the basics of the antd, explore more on he Ant for Reactjs

Following ant design posts deserve good read

How to render child components in Reactjs


Suppose we have components that called inside another in Reactjs , things can be messy. The parent component not render the child by default. Here is our code with two components.

export default class BackgroundDesign extends Component {
    render() {
        return (
            <div
            className="site-layout-content text-al"
            style={{ background: "#a8071a" }}
             
          />       
        )
    }
}

export default class SiteHeading extends Component {
  render() {
    return (
      <div className="site-layout" style={{ background: "#820014" }}>
        <span
          className="p-2"
          style={{ color: "whitesmoke", "font-size": "28px" }}
        >
          I am a Heading
        </span>
        
      </div>
    );
  }
}
 <BackgroundDesign>
            <SiteHeading/>
                It is a about  page.
            </BackgroundDesign>

In the above BackgroundDesign component we used Site Heading component which is not rendered successfully.

How to add element to mongoose object array in Nodejs


Mongoose array can set of objects basically a reference to other mongoose document placed in other document. Our task is to place a new element to MongoDB array of objects.

To add a new element we can use the $push command. In our Post example we had tags which need to added while updating the post.

Post.updateOne({_id:pst},
{
  $push:{'tags':ctag._id}
},
{  safe: true, upsert: true}
) 

$push will add the tag id to the tags object array

Alternatively we can afford the following method too. The difference is that the first one used inside a update command.

post.tags.push(stag)

How to interact with input in Reactjs


With Browser route we can create beautiful responsive React app on the go. Most of the dynamic applications accepts some feed back from users. How do we get this done.

This will involve the following

  • Setting state for the each input element.
  • Attach it to the value property of the input.
  • Add a button event function and attach it to the render method.

Setting State

I have a one input text field and a button in the component.

import React, { Component } from "react"; 
 
class Comment extends Component {
  constructor(props) {
    super(props);    
    this.state = {      
    };
  }
  
  
  render() {
    return (
      <div className="form-group  m-2 p-2">
        <textarea
          placeholder="Comment here"
          class="form-control"          
          aria-describedby="inputSuccess5Status"
        />
        <button
          className="btn btn-primary m-1 p-2"        >
          Comment
        </button>         
      </div>
    );
  }
}

export default Comment;

In the above Comment component I have used bootstrap to beautify the form with one Text Area and button element. We need to create and attach a state for the Text Area in the constructor, also need to attach the new value with the state, whenever the user enter the comment. So we need to setState the comment in the on Change event handler.

  • Create state
  • Create event handler for on Change
  • attach them to the HTML tags
class Comment extends Component {
  constructor(props) {
    super(props);
    this.onChangeComment = this.onChangeComment.bind(this);
    this.onPostComment = this.onPostComment.bind(this);
     
    this.state = {
      comment: "",
    };
  }
  onChangeComment(e) {
    this.setState({ comment: e.target.value });
  }

  onPostComment(e) {
    try {
      
     console.log('Thank for using react form')
    } catch (error) {
      console.log(error);
    }
  }
  
  render() {
    return (
      <div className="form-group  m-2 p-2">
        <textarea
          placeholder="Comment here"
          class="form-control"
          value={this.state.comment}
          onChange={this.onChangeComment}
          aria-describedby="inputSuccess5Status"
        />
        <button
          className="btn btn-primary m-1 p-2"
          onClick={this.onPostComment}
        >
          Comment
        </button>
         <CommentCard  comments={this.props.comments}/>
      </div>
    );
  }
}

In the above code , created a state comment , event handlers for input and button and bind them in the constructor.

In the on Change event update the state so, each time the user update will change the state.

Finally attach the state and handlers to form elements ( button,Text Area).

Where did can I see the log(‘…’) result ?. well ,open your browser , ctrl+shift+I ( for developer tools) then go to console and you will see the message)

Following React posts deserve good read

How to render mongo object in Reactjs


MongoDB objects are object Id of another document stored in the mongo database. 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
}

Our task is to render the user object and access its properties

For simplicity I skip the rest of the component code.

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

React recognize sub document as filed, not as an object. So we have to convert the user to Object ( the highlighted line)

So far we have succeeded to render the MongoDB object

Following React posts deserve good read

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