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

Create REST-API using sequelize-Mysql in Nodejs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MySQL

MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language. A workbench , which GUI tool to manage database object is available at MySQL website along with MySQL Downloads

Todo API

todos table in Workbench

Our API is used to create the todos ,store in MySQL DB , and perform all CURD operations using sequelize modal.

First we need to create the above table in your MySQL. Now lets create a basic Nodejs project.

Continue reading Create REST-API using sequelize-Mysql in Nodejs

Create REST-API using sequelize-Postgres in Nodejs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

PostgreSQL

Postgres is an opensource DBMS, it is free and perform faster results. It come with pg-admin web interface which allows navigate through database. You can download and install it from the official website

Todo API

todos table in pg admin

Our API is used to create the todos ,store in pg (PostgreSQL) , and perform all CURD operations using sequelize modal.

First we need to create the above table in your pg. Now lets create a basic Nodejs project.

Continue reading Create REST-API using sequelize-Postgres in Nodejs

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

How to filter MongoDB object list in express-node app


MongoDB objects are object Id of another document stored in the mongo database. We can place multiple objects using list of object fields. A sample mongo object list as follows.

 "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"
            ],
            "_id": "5fef1f5187a69346300003aa",
            "tagName": "JS",
            "createdAt": "2021-01-01T13:10:41.810Z",
            "updatedAt": "2021-01-01T13:11:15.561Z",
            "__v": 2
        }
    ],

We want to lookup at the above list of tags and make sure no more duplicate tags shown up in the future. A loop will do the job, using a filter we can do the same.

if (post.tags.filter(xtag => xtag == 'ABCD') == false) {
console.log(`No Tag found`);
} else {
console.log(`Tag already added`);
}

The filter uses a quick arrow function to filter result and return false when it failed to match the tag.

Following Mongo posts may help you

How to fix mongo object Type error 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
}

In the above document we want to render the user object and the following code will cause an type error

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: {(this.state.post.user).name}            
     </div>
        </div>
      </div>
    );

TypeError: Cannot read property ‘name’ of undefined

Error Fix

React recognize sub document as filed, not as an object.To fix the error we have to convert the user to Object as follows.

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>
    );

Following React posts may help you

How to create express-routes using controllers


Express is a Nodejs frame work which can be used to create web applications. A route represents a page in the web app or website. An ideal express app consist of multiple web pages.

Prerequisites

We need the following before proceeding to the next step

  • Nodejs, install the Node
  • A Code editor of your choice ( sublimText/Atom/VS-Code)
  • A browser

For simple project we can put all of them inside a single file such as inex.js but it is a good practice to modularize the project with folder and files. So that it help manage the project easily.

The Folder structure

Following are the folder structure for the express project. First create project folder using command prompt or you can use the code editors command

In Atom you can use Shit +A for new folder , A for new file

Project Folder Structure
md express-route
cd express-route
md app
cd app
md controllers

Generate package file for the project with start script. We can use the npm init command for this purpose.

npm init -y 

by default init command will ask you a series of question , we can avoid them and use default values using the -y option.

Also add a start script to the pacjage.json file as follows

  "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node index.js"
},

Create index,controller,routes files

Index.js : This file is the starting point of our project, create a new files with .js under the Project folder

controller.js : controllers hold the definition for the different routes ( Save under the controllers folder)

routes.js : This file where we declare all our express-routes and later use them in index.js (Save under the app folder)

Install the Express

Lets install essential packages for our project , on the shell please issue the following ( make sure you have internet connection)

npm install express --save

Define the controllers

The controller function is a simple java script module consisting of the following (in the file controllers.js)

module.exports = {
home:(req,res)=>{
  try {
    res.status(200).send('This is a Home Page')
  } catch (e) {
    console.log(e);
  }
},
about:(req,res)=>{
  try {
    res.status(200).send('This is a About Page')
  } catch (e) {
    console.log(e);
  }
},
contact:(req,res)=>{
  try {
    res.status(200).send('This is a Contact Page')
  } catch (e) {
    console.log(e);
  }
},
}

Prepare the routes

Let’s create our express-routes using the controller functions ( in the file app/routes.js )

const express = require('express');
const router = new express.Router;
const Controllers = require('./Controllers/Controllers')

router.get('/',Controllers.home)
router.get('/about',Controllers.about)
router.get('/contact',Controllers.contact)

module.exports = router;

Using express-router module we define the routes for our app and also import and utilized the controller functions and finally exported the module and get things ready for the routes in the index.js

Setup server, routes

The final step is to create use the routes and start our Node server (localhost). Now the index.js will look like

const express= require('express')
const app=express()
//routes
app.use(require('./app/routes'))

app.listen(3000, () => console.log('server on!'));

Here we had imported the routes.js as middle ware and will cause implementing all the routes defined in the routes.js file

Run the server

We can run the project using the start script configured in the package file.

npm start

and in the console the server on message will shown. Got to your browser and lunch the app using http://localhist:3000 and also try /about/ and /contact routes.

How to use css in Nodejs-Express project


For using Cascade Style Sheet in Nodejs-Express app make sure the following is done

  1. Create assets folder
  2. place the style sheet inside the folder

Express and the static

In order to use the style sheet with ejs views ( which is a templating system for Express app. Every ejs template is similar to HTML file except optionally it can avoid the tag ( <,>) operator and it carries a .ejs extension), declare the middle ware as follows

app.use('/assets',express.static(assets))

In Ejs template

in a ejs Template we can use the css as follows

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <title>Minimal Blog Engine</title>
       <meta name="description" content="">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" href="/assets/style.css">
       
   </head>
   <body>
   <h1>EJS Template</H1>
   </body>
</html>

and it will work.

These EJS posts may also help you

Reusable partial EJS-templates in Express


EJS is a Express (it is a simple Nodejs framework for developing web apps with multiple routes) templating system. Template system allow us to pass values from JavaScript to Frontend. For example you have a JS which populate price list and want show in front end ( as HTML). It can be done with templating system. It is similar to Ninja template in Python – Flask.

In Ninja templates can be derived from a base template, EJS don’t have such thing , instead we can split the reusable part of the template into partial template which is also have .ejs extension.

We can place them in a separate folder or place ‘_’ before the name to identify, it is an notion not a rule and up to you which one to follow.

EJS Template

In our example we have New Post form template as follows

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <title>Minimal Blog Engine</title>
       <meta name="description" content="">
       <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">
   </head>
   <body>
 
  <div class="container">
  <h1 class="mb-4">New Post</h1>
 
  <form action="/posts/" method="POST">
  <%- include('_form_fields.ejs') %>    
  </form>
  </div>
       
   </body>
</html>

The in the include tell the template to render the HTML

Partial template

In the above EJS template the <% include %> statement call a partial template. Let’s create it with few input fields.

<div class="form-group">
<label for="title">Title</label>
<input type="text" required name="title" id="title" class="form-control" ">
</div>
<div class="form-group">
<label for="excerpt">Excerpt</label>
<textarea type="text" name="excerpt" id="excerpt" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="Markdown">Markdown</label>
<textarea required rows="5" cols="" type="text" name="markdown" id="markdown" class="form-control"> </textarea>
</div>
<a href="/" class="btn btn-default">Cancel</a>
<button type="submit" class="btn btn-primary">Save</button>

_form_fields template only define necessary part of form. It can be used with any form which require those fields using the Include statement . So the reusability purpose is served .

Todo : Try to move the head section to a partial template

You may also like the following express posts

How to interact with input in Reactjs - How to handle state and event of input element in React apps
Create REST-API using sequelize-Mysql in Nodejs - How to create REST-API using sequelize-MySQL ORM in Node-Expressjs
Create REST-API using sequelize-Postgres in Nodejs - How to create REST-API using sequelize ORM in Node-Expressjs
How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
How to render mongo document in Reactjs - How to render mongo document in react component
How to filter MongoDB object list in express-node app - How to filter a mongo object list in document in express-node app
How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
How to create express-routes using controllers - How create a express-routes systematically using controllers and routes
How to use css in Nodejs-Express project - Learn how to use CSS/Bootstrap in Express-EJS templates
Reusable partial EJS-templates in Express - Learn how to build web/static-blog app with Express and EJS reusable /partial templating system