Posts on this Category



How to load a JSON file in NodeJS

This is another short, but useful tutorial for beginners. In this post I’m going to show how to load the following JSON dataset with NodeJS:

dataset.json

[{"id":1,"first_name":"Philip"},
{"id":2,"first_name":"Dorothy"},
{"id":3,"first_name":"Kathleen"},
{"id":4,"first_name":"Arthur"},
{"id":5,"first_name":"Robin"},
{"id":6,"first_name":"Douglas"},
{"id":7,"first_name":"Theresa"}]

We don’t have to create an entire project with express to read this file, a simple js file will do.

node-json.js

 var fs = require("fs");
 
 var jsonAsString = fs.readFileSync("dataset.json");
 var jsonArray = JSON.parse(jsonAsString);
 
jsonArray.forEach(function(row){
  console.log("Id:", row.id);
  console.log("Email:", row.first_name);
});

To load the file we have to provide url to the function readFileSync from fs (File System), it’ll return the content as an string. Before we can use it we just have to convert it to JSON with JSON.parse.

You can execute your code via the command: node node-json.js. If it works it’ll print all the json data on your terminal.

How to Set up a Database connection with ReactJS

The short answer to this question is: You shouldn’t use React to connect directly to your database. React is a front-end framework, it should only be responsible for the user interface. If you need a database connection, the right place for it is the back-end, that’s also where you’re going to fetch and process the data before you provide it to the presentation layer.

Now let me show you how to do that. In this example I’m using PosqgreSQL database and Node.js with Express on the server-side.

const express = require('express')
const app = express()
const { Pool, Client } = require('pg')
const pool = new Pool({
   user: 'postgres',
   host: 'localhost',
   database: 'db',
   password: 'pw',
   port: 5432,
})
 
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});
 
app.get('/data', (req, res1) => {
      pool.query('SELECT id, description FROM products', (err, res) =>{
      if (err) {
	 console.log(err.stack)
      } else {
         res1.send(res.rows)
      }
   })
})
 
app.listen(3001);
 
module.exports = app;

This is the simplest possible example on how to connect and execute queries. I’ve used the node-postgres module to be able to interact with PostgreSQL, so don’t forget to install it on your NodeJS project.

Since you’re here because of React, I don’t want to get into details about NodeJS in this post, and as far as I know, lots of you aren’t even using NodeJS in the back-end. So all we need to know here is that our node application will provide data from the database via the following link: http://localhost:3001/data. Now let’s see how to use this link on the React project.

import React, { Component } from 'react';
import './App.css';
 
class App extends Component {
 
  constructor() {
      super();
      this.loadData();      
  }
 
  loadData(){
    this.state = { data: [] };
    fetch('http://localhost:3001/data') 
      .then(result=>result.json())
      .then(data=>this.setState({data}));
  }
 
  render() {
    return (
      <ul>
        {this.state.data.map(item=><li>{item.id} - {item.description}</li>)}
      </ul>
    );
  }
}
 
export default App;

In this example we have a very simple React component. Take a look at the loadData method, that’s where we are getting the data from the server. I’m using the fetch API to make the request, so all we have to do is provide the link and it will return the data for us. When it receives the response I’m storing the result in the local state so I can access it from the render method and present it as I like, in this case I’m showing the data as a list.

That’s it guys!! Hope you liked the tutorial, I tried to keep this post simple, so maybe it wasn’t as detailed as you expected, but if you have any doubts please don’t hesitate to ask, just leave a comment and I’ll do everything I can to help you.

Node.js: How to make POST Requests with JSON data

In this post I’m going to show you how to work with POST requests, I’ll give you an example as simple as possible. First I’ll create the Nodejs app to receive the requests, then I’ll show you how to make the requests from the frontend.

We’re going to be using Expressjs, it’s a very popular npm package, you probably already heard of it, but if you don’t, just click here to see the instructions on how to create your project. You can also add express to an existing project via npm, but in this case you’ll have to add the body-parser as well.

Express creates a basic project structure for us, but most of it will not be used in this example, so I’m going to open my app.js and get rid of almost everything, this is the minimum we need to create requests routes:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
<pre lang="javascript">
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
 
module.exports = app;

Now let’s create our first route, I’m putting it at the end, right above the module.exports line:

app.post('/test', (request, response) => {
   console.log(request.body);
   response.json(request.body);
});

Here I’m using the express post function to create the route, it receives the path, which in this case is /test and a callback function to handle the request. Note that this function has two parameters, request and response. The first contains the JSON data passed by the client, it can be accessed through the attribute body. The second is where we put the result, so the client can receive it when the request completes.

In this example, after receiving a request the server will print the JSON dataset sent by the client and then send back the exact same data.

Ok, we’re done with the server-side now, let’s see how to make requests with the Fetch API on the frontend.

var data = [{"username": "dmccreadie0"}, 
   {"username": "bwillerson1"}, 
   {"username": "fteese2"}, 
   {"username": "dsummerell3"}];
 
fetch('http://localhost:3000/test', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {'Content-Type': 'application/json'}
}).then(response => { 
  return response.json(); 
}).then(data => { 
  alert(JSON.stringify(data));
}).catch(err => {
    alert(err);
});

The variable data is a simple JSON dataset I’ve created to use as an example. When making a request with fetch() we have to pass the URL, which in this case is http://localhost:3000/test, and an object containing the request options (method, body and header). To include the JSON data in the request we have to convert it to string and assign it to the body attribute, this way the server will be able to retrieve this data as we saw before.

Lastly, let’s see how to get the data sent by the server. The function then() allows us to add a callback that handles the response. To retrieve our data we just have to use the function json(). In this example I’m just extracting the JSON from the response and showing it to the user with an alert dialog.

That’s pretty much it guys, of course there’s much more we can do here, it’s a big topic, but as I said this is just a basic example. If you have any doubts don’t hesitate to ask in the comments.

Express.js: How to Change the Default Port

By default Express uses port 3000, but sometimes this port is already been used by another application, so you can either close the other application or change the port. In this short tutorial I’m going to show you how easy it is to change the port.

First let’s open the bin/www file and locate this code:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

Here is where we can configure which ports to use, all you have to do is to replace the number 3000 by another port number. After that your application will not be using port 3000 anymore.

Alternatively you can also configure the port on your app.js:

var app = express();
app.listen(4000);

As you can see I’ve just added the app.listen(4000) line, this will make the application also listen on port 4000, but the difference is that this method won’t make your app stop using port 3000.

It’s up to you to decide which method works better for you, If you have any doubts please let me know in the comments.

How to use Bootstrap in a Reactjs project

Styling is a little bit different in Reactjs, so you cannot use Bootstrap in a traditional way. In this tutorial I’m going to show you an easy way to add Bootstrap to a Reacjs project. As we can’t use the traditional Bootstrap we have to use another version called React-Bootstrap, it’s basically the same framework, but it was rebuilt so we can use it with React. You can install it in your project via:

npm install --save react-bootstrap

React-bootstrap doesn’t come with the CSS, so you have to add it manually to your index.html:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">

Ok, we’re already done with the setup. Now we’re ready to import the components and start using them. To give you an example of how to do that I’m going to import the Bootstrap FormControl component and use it in my project.

import React, { Component } from 'react';
import FormControl from '../node_modules/react-bootstrap/lib/FormControl';
 
class Field extends Component {
  render() {
    return (
        <FormControl type="text"/> //<-- This is equivalent to <input class="form-control" type="text"/>
    );
  }

Note that in line 2 I’m importing the FromControl from the react-bootstrap folder inside the node_modules. I recommend you to check this folder so you can see all the components you have available. If you run your project now you’ll see the bootstrap input you’re used to.

That’s pretty much it, of course not every react-boostrap component will be as simple as this one, so if you have any doubts on how to use them please let me know in the comments.

Reacjs Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + ’em’}} when using JSX

This error occurs when you try to pass regular CSS strings to the style attribute of an HTML element. In React, the styling is different, instead of an string the style attribute expects an object.

So instead of doing this:

<p style="font-size: 12px; color: black" >text</p>

you should do this:

var pStyle {
   fontSize: '12px',
   color: 'black',
};
<p style={pStyle} >text</p>

Note that the name of some CSS attributes are a little bit different in React, you should always write them camelCased. As you can see in this example the font-size attribute became fontSize.

That’s pretty much it! Hope it helps.

Reactjs Error: Adjacent JSX elements must be wrapped in an enclosing tag

This is a very common Reactjs error, specially for beginners. If you are getting this error you code probably looks like this:

class App extends Component {
  render() {
    return (
        <Component1></Component1>
        <Component2></Component2>
    );
  }
}

The problem is that your render function is returning two elements, it’s equivalent to adding two return statements to your function, and reactjs won’t allow that.

The solution is very simple, you just have to add an enclosing tag as described in the error message. After this modification the code should look like this:

class App extends Component {
  render() {
    return (
      <div>
        <Component1></Component1>
        <Component2></Component2>
      </div>
    );
  }
}

As you can see I’ve added a div as an enclosing tag, now the function is returning only one element. This this should fix the problem, but if it doesn’t please let me know in the comments.

Nodejs Totorial: Creating and Using Events

Nodejs makes it very easy for us to use events, and we’re not limited to a collection of predefined events, it has a built-in module that allows us create and emit our own events.

Let me show you how easy it is to use this module, first we have require the events module and create the event emitter:

var ev = require('events');
var emitter = new ev.EventEmitter();

Ok, now we’re ready to start creating the events. As an example I’m going to use an event that I named new user, let’s create its event listener:

emitter.on('new user', function(){
   console.log('A new user has connected.');
});

I’ve used the function on from the EventEmitter to add this event listener, it receives the event name and a callback function that executes once the event is triggered.

Now the application is already listening the new user event, this is how we can emit it:

emitter.emit('new user');

Simple right? All we have to do is to call the emit function passing the event name.

But what if we have to pass parameters when emitting the event? Optionally, you can also pass some arguments to the emit function if you need, then you just have to declare them on the callback function as well. Here’s an example:

emitter.on('new user', function(user){
   console.log('The user '+user+' has connected.');
});
 
emitter.emit('new user','user1');

That’s it guys! Thanks for reading, if you have any doubts please let me know in the comments.

Tutorial: How to create an Overlay Panel

Overlay Panel
Overlay Panel

Today I’m doing another webdesign tutorial, this time I’m going to be showing you how to create an overlay panel. There are lots of ways you can use it, one of then is as a dialog, like in image above.

So let’s start with the HTML structure:

<div class="overlay_panel">
	<b>Overlay Panel</b>
	<p>Phasellus vel metus iaculis mauris condimentum imperdiet. Praesent feugiat fermentum 
           aliquet. Mauris porttitor, nisl at eleifend sodales, eros ex eleifend arcu, sit amet 
           molestie dui neque non tellus. In hac habitasse platea dictumst. Nunc quis accumsan 
           nisi. Donec at congue ante. Morbi laoreet a leo eget pharetra. Aenean scelerisque c
           onsequat vehicula. Sed quis condimentum arcu. Quisque pulvinar mauris eget sapien so
           llicitudin, vitae blandit lectus pellentesque. Nullam at nibh rhoncus, feugiat tellu
           s ut, iaculis velit.
        </p>
	<a href="#" onclick="hide()">OK</a>
</div>

The only thing that matters here is the div with the overlay_panel class, you can put anything you want inside it. As an example I’ve put a title, a text and an ok button.

Now let’s do the styling:

.overlay_panel {
    position: fixed;
    top: 0; 
    left: 0;
    right: 0;
    bottom: 0;
    margin: 100px auto;
    width: 50%;
    display: none;
    border-radius: 2px;
    text-align: justify;
    background-color: white;
    color: #333;
    padding: 20px;
    box-shadow: 2px 2px 10px 2px #333;
}
.overlay_panel a{
	float:right;
}

You can adjust the width, height, color and pretty much everything else as you like, but you should keep the display: none to make it hidden by default, and also the position: fixed, which will position your panel in front of your page content.

Lastly, this is how to show/hide it:

function show() {
    document.getElementsByClassName("overlay_panel")[0].style.display = "block";
}
 
function hide() {
    document.getElementsByClassName("overlay_panel")[0].style.display = "none";
}

These two functions just switches the display from none to block, and vice versa. Note that I’ve used the function getElementsByClassName to get the element, but it returns an array, so I had to specify the index to access my element. Alternatively, you could use getElementsById function, which returns only one element.

How to load a JSON file in Reactjs

It’s really easy to load data from a JSON file in React. In this post I’m going to show you how you can do that. First, of course, we need a JSON file, you probably already have yours, but I’m using this movies list for this example:

data.json

[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Now we have to place this file somewhere inside our project folder, it doesn’t necessarily need to be on the project, but it must be somewhere accessible via Http.

Once you have the path to your file you can load it this way:

import React, { Component } from 'react';
import data from './data.json';
 
class App extends Component {
  render() {
    return (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}
 
export default App;

Note that all I had to do was to import the file in line 2, then the data was already ready for me to use on the data variable. Lastly, to show you how to use this variable I’ve made this component iterate over the dataset and display it on a list.

Easy right! If you have any doubts please let me know in the comments.