Posts on this Category



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.

Tutorial: Creating a Realtime Notification System in Angular and Nodejs

Notification System Demo
Notification System Demo

In this post I’m going to show you how to create a simple realtime notification system using Angular, Nodejs and Socket.io. It will offer a page where we will be able to create notifications and broadcast it to all the online users. I’ll be making it as basic as possible, once we’re done we can add more functionalities. This application will have the frontend and the backend separeted in 2 different projects, we’re going to use Angular in the frontend and Nodejs in the backend. Let’s start with the backend.

Creating the Nodejs Project

I’m using Expressjs to create the Node.js project, if you don’t have express you can install it globally via:

npm install express-generator -g

After installing it you can create your project with the command:

express notifications-backend

In this case ‘notifications-backend’ is the project name, but you can give a name of your choice. Now you already have a basic expressjs project, if you run your project with npm start and type the url localhost:3000 on your browser you’ll see a welcome page. By default expressjs create some views for us, we’re not going to be using them though, so feel free to delete them if you want. All of our views will be on the frontend project, this one will only be responsible for managing the notifications.

Creating the Socket.io Server

The next step is to add socket.io to the project:

npm install --save socket.io

Socket.io is what makes our application realtime, it’s event-based, which means when an event happens, it triggers something. All the events are specified by us, we can create as many as we want, but our application only needs two, I’m going to name them create notification and new notification.

create notification: This event will be emitted by the client-side when a user creates a notification. The server will always be listening to this event, this is how it will know a notification was created.

new notification: This one will be emitted by the server-side when it receives a newly created notification. As opposed to the previous event, this one will be listened by every client, once they receive this event they will just show the notification to the user.

This is our server-side socket.io code, I’m putting it on the app.js just bellow the var app = express(); line.

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set("origins", "*:*");
server.listen(8000);                                 
 
io.on('connection', function(socket){                
  socket.on('create notification', function(data){   
    socket.broadcast.emit('new notification',data);  
  });
});

Before we analyze the code we should know the socket.io on function, that’s the function we use to add event listeners to the application, it receives the event name and a callback function that will be executed when the event fires. You should also be familiar with the function emit and broadcast.emit, the first one emits an event to all the clients as the second emits to everyone except the client who fired it.

Now If you take a look at the code you’ll see that the first 5 lines are just to create the socket server, next I’m adding an event listener to the connection event, so every time a new client connects this event will call a callback function that adds a listener to the create notification event, which when triggered will emit the new notification event broadcasting the message to all the users.

We are pretty much done with the backend now, time to start working on the frontend!

Creating the Angular Project

If it’s the first time you’re using Angular you have to install @angular/cli before you proceed.

npm install -g @angular/cli

Now you can create your project.

ng new notifications-frontend

Again, notifications-frontend is my project name, you can change it if you want. The command above will download and install all the dependencies on your project, so it may take a while. After creating the project we have to install socket.io on this one as well, but the installation is a little bit different from the backend, click here to see the instructions.

Now we have the basic project structure, we’ll be creating two components, app.adminComponent.ts and app.userComponent.ts, the first one is the page where the admin will be able to send notifications to all the other users, and the second is a component that represents any page that a user have access to, its only functionality will be to receive the notification.

app.adminComponent.ts

import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
 
@Component({
  selector: 'admin-component',
  templateUrl: './app.adminComponent.html'
})
export class AdminComponent {
 
   constructor(private socket: Socket) {}
 
   sendNotification(){
      this.socket.emit('create notification','Notification Test');
   }
}

Here we have the admin-component, note that I’m declaring the socket on the constructor, besides that I’ve created only one function, the sendNotification, which will be responsible for emitting create notification event. Remember when we created its listener on the server side? This is how it’s going to be triggered.

You have probably noticed that this component uses a template. Here is the code:

<div style="text-align:center">
   <button (click)="sendNotification()">Send Notification</button>
</div>

Nothing special here, it contains only a button that calls the sendNotification function.

app.userComponent.ts

import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
 
@Component({
  selector: 'user-component',
  template: ''
})
export class UserComponent {
 
   constructor(private socket: Socket) { 
      socket.on('new notification', function(data){
         alert(data)
      });
   }
}

This one is even simpler than the previous, the only thing I’m doing here is adding an event listener to the new notification event, which is the event for receiving a notification. Once it fires it will show the notification message to the user with an alert dialog.

Routing and Navigation

We’re almost done, the last thing we have to do is to add the routes, that’s what will allow us to navigate between the two components. We will define two routes, user and admin, so our components will be accessed by the urls http://localhost:4200/user and http://localhost:4200/admin respectively.

Here is how we can define the routes on the app.module.ts file:

//other imports
import { RouterModule, Routes } from '@angular/router';
 
const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'admin', component: AdminComponent },
];
 
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes),
    //other imports
  ],
  ...
})
export class AppModule { }

As you can see I’ve created the array appRoutes, here is where we declare all of our routes mapping the paths to the components, then we pass it to the RouterModule.forRoot function on the module imports.

Lastly let’s open the app.component.ts, that’s the default component that was already there when we created the project. We’re only using this component to put the router-outlet, which will just display the component that matches the path on the Url.

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
    <router-outlet></router-outlet>
  `
})
export class AppComponent { }

That’s it guys! Your application should be working now, hope you liked the tutorial. If you have any doubts please let me know in the comments.

How to add Socket.io to an Angular application

Lots of people get confused when trying to use Socket.io with Angular, some developers just add the script to the HTML and start using it, even though it works I don’t recommend doing this way, let me show you the right way to use it with Angular.

After creating your angular project install ng-socket-io via:

npm install ng-socket-io --save

This is an Angular specific Socket.io module. After the installation is complete you have to configure socket.io in your app.module.ts, you basically just have to add the imports and inform the server url:

...
import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';
 
const config: SocketIoConfig = { url: 'http://localhost:8000', options: {} };   <-----------------
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config)     <-----------------
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Next, open the tsconfig.json and add the “include” attribute at the end, this will prevent some errors when building your project. Make sure the file looks like this:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "include": [
    "src/**/*",
    "node_modules/ng-socket-io/index.ts"
  ]
}

That’s it! Now you just have to import it to your component and start using it:

//importing 
import { Socket } from 'ng-socket-io';
 
//usage example
constructor(private socket: Socket) { 
   socket.emit('test','test');
}	
}

Node Express Error: Cannot find module ‘serve-favicon’

This error means you don’t have the module ‘serve-favicon’ installed on your project, here is the full error:

Error: Cannot find module 'serve-favicon'
    at Function.Module._resolveFilename (module.js:542:15)
    at Function.Module._load (module.js:472:25)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\project\a2-notifications\app.js:3:15)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! notifications@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to in
stall?

Buf if you are getting this error the ‘serve-favicon’ is probably not the only module missing. My guess is that you forgot to install the dependencies before running your project with npm start. Try executing npm install first, this command will download all the dependencies for you, after that your problem should be solved.

@angular/cli error when creating project: Unexpected token =

After installing @angular/cli lots of people get this error when trying to create the fist angular project:

SyntaxError: Unexpected token =
   at exports.runInThisContext (vm.js:53:16)
   at Module._compile (module.js:373:25)
   at Object.Module._extensions..js (module.js:416:10)
   at Module.load (module.js:343:32)
   at Function.Module._load (module.js:300:12)
   at Module.require (module.js:353:17)
   at require (internal/module.js:12:17)
   at Object.<anonymous> (C:\Users\a\AppData\Roaming\npm\node_modules\@angular\cli\models\config.js:3:18)
   at Module._compile (module.js:409:26)
   at Object.Module._extensions..js (module.js:416:10)

The solution is very simple, just download and install the newest version of nodejs, this should fix the problem.

How to Load a JSON file in Javascript

In this post I’m going to give you a very simple example of how to read a JSON file and display the data on the page. I’ll be using jQuery in this example, so if you don’t have it on your project don’t forget to add the script.

So let’s get started, first we need a JSON, you probably already have yours, but for this example I’m using this one:

data.json

[{
  "id": 1,
  "first_name": "Larry",
  "last_name": "Gebhardt"
}, {
  "id": 2,
  "first_name": "Dorothy",
  "last_name": "Portress"
}, {
  "id": 3,
  "first_name": "Selby",
  "last_name": "Rudolfer"
}, {
  "id": 4,
  "first_name": "Coraline",
  "last_name": "Aspel"}
]

This file has to be placed somewhere accessible via HTTP, I’m putting it on the same folder my HTML page is located.

jQuery provides the function getJSON for us, it receives two parameters: the JSON url and a callback function to handle the data. Here’s how we can use it:

 
jQuery.getJSON("data.json", handleJSON);
 
function handleJSON(result){
   jQuery.each(result, printFields);
}
 
function printFields(i, field){
   let row = field.id + " "+field.first_name + " "+field.last_name + " <br>";
   jQuery("div").append(row);
}

First I used jQuery.getJSON to retrieve the data, once we have the result it is passed to the function handleJSON, which is using the jQuery.each to go through the data. Each item from the dataset will be passed to the printFields function, which creates a string with all the fields and append it to an HTML component.

Easy, right? If you run your project now you’ll see the data on your page. If you have any doubts please let me know in the comments.

Error: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https

If you are facing this error it’s because your page is trying to load a local file using file:// or C:/ (you can see it in the URL on your browser). It happened to me one time, that’s because I created a HTML page and simply double-clicked on it to open it on the browser, my page was using a JSON file from the same folder, and when I checked the console this error was there:

Failed to load file:///C:/project/myProject/data.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Turned out I needed a webserver for this. The solution was to install one on my computer (WampServer or Lamp will do fine) and host my page on it, this fixed the problem for me.

Tutorial: How to Create Cards UI with CSS & HTML

Cards Demo
Cards Demo

In this short tutorial I’m going to show you how to create cards, they are trending for quite some time now and I thought it would be a good idea to write about them. For this example I’m only using HTML and CSS, my goal here is to just show you how to create the design. Please let me know in the comments if you want another post on how to add animations and some functionalities to it.

So first let’s create our HTML structure, as you can see in the image above, our cards will be composed of an image and a description containing a title and a small text. This is how it should look like in code:

<div class="card">
   <img src="img.jpg" >
   <div class="description">
      <h4 class="title"><b>magna tincidunt et</b></h4> 
         <p class="text">Nam nec lorem eu nibh aliquam egestas non lobortis neque. 
            Ut tristique tortor sem, eget tristique lectus consectetur id. 
            Vivamus sem metus, fermentum in orci ut, rhoncus semper tellus. 
            Praesent eget porttitor metus. Phasellus a ipsum vulputate, cursus massa eu, 
            tincidunt purus. Curabitur auctor vulputate velit</p> 
   </div>
</div>

Don’t forget to pick an image and specify it on the img src attribute. Now we already have our card, it’s not very pretty, though. Let’s add some style to it:

.title, .text{
   font-family: verdana;
   font-size: 12px;
}
 
.title{
   margin-bottom: 0px;
}
 
.text{
   margin-top: 5px;
}
.card {
   box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
   transition: 0.3s;
   width: 300px;
   margin: 3px;
   float: left;
}
 
.card:hover {
   box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
}
 
.description {
   padding: 2px 16px;
}
 
.card img{
   width:100%;
}

Now just add this CSS to your page. I styled my card this way but feel free to edit this CSS as you like.

That’s it guys! We’ve created a very basic card, as I said before let me know in the comments what functionalities do you want it to have.

How to put Objects on HTML5 sessionStorage/localStorage

HTML5 sessionStorage and localStorage only allows you to store strings, but sometimes it’s very convenient to add more complex values like arrays and objects. Here a simple way to do that:

var array = [];
array.push('a');
array.push('a');
array.push('c');
 
// Put object on sessionStorage
sessionStorage.setItem('key', JSON.stringfy(array));
 
// Get object from sessionStorage
var object = JSON.parse(sessionStorage.getItem('key'));

As you can see in the example I’ve just converted my array to a string before storing it in the sessionStorage, then I converted it back to an array when I retrieved it from the sessionStorage. This was a very simple workaraound, hope it helps!

Angular2: How to Pass Callback Functions to a Component

There are lots of situations where it’s useful to pass a function to an angular2 component, for instance, when our component is a dialog and we have to perform an specific task when it closes, or pass the action of one of its buttons, or even events like keypress, resize, mouseover, etc. If you’re reading this tutorial I’m sure you came across your own situation.

As an example I’m going to create a component with just a button, when clicked it will execute the callback function passed to the component, simple as that. Now let’s see the code:

@Component({
  selector: 'my-component',
  template: `
     <button type="button" (click)="callback()" >Callback Test</button>
  `
})
export class MyComponent { 
 
   @Input() callback: Function;
 
}

The first thing we have to do is to create a variable so we can assign the callback to it, in this example I’ve declared the variable callback and specified it to be a Function, I’ve also decorated it with @Input(), this will allow us to pass our function to this component. We can use this variable in the template as if it were a regular function, as you can see I’m binding it to the button click event like this: (click)="callback()".

Now let’s see how to pass our function to the component:

@Component({
  selector: 'my-app',
  template: `
  	<my-component  [callback]="showMessage"></my-component>
  `,
})
export class AppComponent { 
   showMessage(){
      alert('Callback Test');
   }
}

First, of course, we must have a function, in this case I’ve created the showMessage(), we can pass it by just adding [callback]="showMessage" to the component on the template, this binds the showMessage function to the callback property we saw on the previous component.

Now if you run the application you’ll see that the showMessage() is called when you click on the button.