HTML5 web sockets provides stable connectivity to servers. By using these web sockets we can setup a stable connection between browser and sever, and then we can send or receive messages.

Like shown in below image, users send and receive messages on real time


Observe below GIF, One is chrome and another is firefox, Whatever we type in chrome, that will be displayed in firefox.

Lets write java program for sharing editor

Java Program

To run below program, you need add java_websocket dependency. Here it is the maven dependency xml.
<dependency>
  <groupId>org.java-websocket</groupId>
  <artifactId>Java-WebSocket</artifactId>
  <version>1.3.0</version>
</dependency>

Once you install the above dependencies, run below program
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class App extends WebSocketServer {

    private static int TCP_PORT = 4444;
    private String value = "";

    private Set<WebSocket> conns;

    public App() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<WebSocket>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        conn.send(value);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        value = message;
        for (WebSocket sock : conns) {
            sock.send(message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }
    
    public static void main(String[] args) {
        new App().start();
    }
}

HTML Code 

This code contains textarea element. Whatever user types in that textarea, it will be sent to java web socket server. Java server will send that message to all its connections. That is how one user's text will be shown to all users. 
<!DOCTYPE html>
<html>
    <head>
    <style>
        .layout {
            width:800px;
            margin:auto;
        }
        
        textarea {
            max-width:800px;
            width:80%;
            border:1px solid #ccc;
            font-size:14px;
            height:400px;
        }
    </style>
    <script>
        var ws = new WebSocket("ws://127.0.0.1:4444/");
        var elm = document.getElementById('myTextArea');
    
        ws.onopen = function() {
            console.log("Opened!");
        };
    
        ws.onmessage = function (evt) {
            myTextArea.value = evt.data;
        };
    
        ws.onclose = function() {
            alert("Closed!");
        };
    
        ws.onerror = function(err) {
            alert("Error: " + err);
        };
    
        function share(event) {
            ws.send(event.target.value);
        }
    </script>
    </head>
    <body>
       <div class="layout">
        <h1>Sharing editor</h1> 
        <textarea id="myTextArea" onkeyup="share(event)" rows="100" cols="50"></textarea>
       </div>
    </body>
</html>
Read More
react-bootstrap-date-time-picker is built on react-bootstrap and moment, so make sure that you have react-bootstrap and moment in your modules.  Lets see some code.

Install

npm install react-bootstrap-date-time-picker --save

Import

import DateTimePicker from 'react-bootstrap-date-time-picker';

Main Features

  • Can be used as simple date picker
  • Can be used as simple time picker
  • Can be used as simple date-time picker
  • Calendar placement
  • Restricting date-time range

Properties

Here are some important properties of DateTimePicker
  1.   defaultValue - string - default input value
  2.   value - string - input value
  3.   onChange - callback function on change of input value
  4.   onClear - callback function on clear of input value
  5.   onBlur - callback function on blur of input
  6.   onFocus - callback function on focus of input
  7.   autoFocus - bool - setting focus automatically
  8.   disabled - bool - disabling input value
  9.   showClearButton - bool - showing clear button
  10.   calendarPlacement - string - calendar placement, ex: "top", "bottom"
  11.   dateFormat - string- input format, ex: "MM/DD/YYYY HH:mm:ss"
  12.   showTodayButton - bool - showing To Day button calendar ,
  13.   todayButtonLabel - string - To Day button text
  14.   from - Date - lowest possible date for selection
  15.   to - Date - highest possible date for selection
  16.   calendarOnly - bool - If you want to display as only calendar
  17.   timeOnly - bool - If you want to display as only time

Limit Range

The default range is 20 years (10 years back from current date to 10 years after from current date). You can give your own range by passing from and to values. Observe below code 
<DateTimePicker 
 from={new Date("2017-03-15T14:28:06+05:30")} 
 to={new Date("2017-03-30T14:28:06+05:30")} 
 onChange={this.handleChange} 
 value={this.state.date} 
/>

Date Format

Here this library uses momentjs for formatting the date string, So just follow the same formate specifications. Here are some useful formats
  1. DD/MM/YYYY - It will show just date
  2. DD/MM/YYYY HH:mm:ss - It will show date and time 24 hours format
  3. DD/MM/YYYY hh:mm:ss A - It will show date and time 12 hours format
You can follow your own customised date formats based on momentjs
<DateTimePicker 
 dateFormat="DD/MM/YYYY hh:mm:ss A"
/>

Display Calendar only 

Use calendarOnly property to display calendar only and hiding time
<DateTimePicker 
 calendarOnly={true}
/>

Display Time Only

Use timeOnly property to display time only
<DateTimePicker 
 timeOnly={true}
/>

Show or hide clear button

Use showClearButton property to display or hide clear button. Here if you should pass dateFormat, from and to
<DateTimePicker 
 showClearButton={false}
 dateFormat="HH:hh:ss"
 from={fromValue}
 to={toValue}
/>
Read More
This React library allows you to enlarge part of an image with a CSS3 based magnifying glass effect. When user mouse over on the image, it will show original enlarged image in magnifying glass. 
react-tweet-parser source on Github       DEMO

Install react-magnify

npm install react-magnify --save

Import Magnify

import Magnify from 'react-magnify';

Properties

It supports all image properties. src property is mandatory property 
  1. src - source of the image

Usage

Use Magnify component like below
<Magnify style={{
          width:'200px'
        }} src="http://thecodeplayer.com/uploads/media/iphone.jpg"></Magnify

Full Example 

Find below for full example
import React from 'react';
import Magnify from 'react-magnify';
import '../../node_modules/react-magnify/lib/react-magnify.css'

export default class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div style={{
        width:'500px',
        margin:'auto'
      }}>
        <h1>It Works with react-magnify</h1>
        <Magnify style={{
          width:'200px'
        }} src="http://thecodeplayer.com/uploads/media/iphone.jpg"></Magnify>
      </div>
    )
  }
}
Read More
By including this component, you can show overflown items in popover.  Lets see how to use this library. This library built on top of react-bootstrap so you should install react-bootstrap to use this

Using npm

npm install react-fit-items-popover --save

Import Component

import FitItemsPopover from 'react-fit-items-popover';

Usage

Here you can pass maximum width, popoverPlacement, popoverClassName, title, items
<FitItemsPopover 
  title="Countries"
  maxWidth="250px"
  popoverPlacement="top"
  popoverClassName="myCustomPopoverClass"
  items={['Iceland','India','Indonesia','Iran','Iraq','Ireland']}>
</FitItemsPopover>

Full example 

Here you can find the full example
import React from 'react';
import FitItemsPopover from 'react-fit-items-popover';
import '../../node_modules/bootstrap/dist/css/bootstrap.css'
import '../../node_modules/react-fit-items-popover/lib/react-fit-items-popover.css'

export default class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>It Works </h1>
        <h3>FitItemsPopover example with popover placement</h3>
        <FitItemsPopover title="Countries" popoverPlacement="right" maxWidth="200px" items={['Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy']}></FitItemsPopover>
      </div>
    )
  }
}
Read More
By including this component, you can show tooltip on text overflow. Lets see how to use this library. This library built on top of react-bootstrap so you should install react-bootstrap to use this

Using npm

npm install text-overflow-tooltip --save

Import component

import TextOverflowTooltip from 'react-text-overflow-tooltip';

Usage

Here you can pass maximum width, style, className, tooltip (popover) placement 
<TextOverflowTooltip 
   maxWidth="100px" 
   style={} 
   className="myCustomClass">give some overflow text here
</TextOverflowTooltip>

Full Example

Here you can find full example. 
import React from 'react';
import TextOverflowTooltip from 'react-text-overflow-tooltip';
import '../../node_modules/bootstrap/dist/css/bootstrap.css'
import '../../node_modules/react-text-overflow-tooltip/lib/react-text-overflow-tooltip.css'

export default class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>It Works </h1>
        <p>Mouser hover on below text</p>
        <TextOverflowTooltip maxWidth="100px">give some overflow text here</TextOverflowTooltip>
      </div>
    )
  }
}
Read More
Generally we use regular expression to validate phone number which fails in many cases.  For example +91 9677146866 is the correct number which exists, +91 2677146866 is also correct number which doesn't exists. Our regular expression shows both as valid phone numbers. For accurate phone number validation, we will use google-libphonenumber library.

Phone number field with country code

Observe below image. Provide field for country code and number

Validating Phone number with google-libphonenumber

Import Utils from google-libphonenumber
import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

validatePhoneNumber(phoneNumber) {
  /*
  Phone number validation using google-libphonenumber
  */
  let valid = false;
  try {
    const phoneUtil = PhoneNumberUtil.getInstance();
    valid =  phoneUtil.isValidNumber(phoneUtil.parse(phoneNumber));
  } catch(e) {
    valid = false;
  }
  if(valid) {
    // do something
  } else {
    // do something
  }
}

Get Valid Phone number in international format

When save numbers in database, you better save them in single international format than many formats. Here is the piece of code which converts normal phone number to international format. 
getValidNumber(phoneNumber) {
  const phoneUtil = PhoneNumberUtil.getInstance();
  const parsedNumber = phoneUtil.parse(phoneNumber);
  return phoneUtil.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)
}

CallingCodes.js

This file contains all country codes, which will be passed to react-select component as options
export default [
    {country : 'Afghanistan',   value : '93',   code : 'AF'},
    {country : 'Albania',   value : '355',  code : 'AL'},
    {country : 'Algeria',   value : '213',  code : 'DZ'},
    {country : 'American Samoa',    value : '1-684',    code : 'AS'},
    {country : 'Andorra',   value : '376',  code : 'AD'}
    .........
];
Using react-select component create Select component for selecting country code
<Select value={this.state.country} onChange={this.onSelect2} placeholder="country code"
               options={CallingCodes} labelKey="country" valueKey="value" valueRenderer={(country) => country.value}>
</Select>

Complete component code

import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-select/dist/react-select.min.css';
import './phone-number.css';
import React from 'react';
import CallingCodes from './CallingCodes';
import {FormControl} from 'react-bootstrap';
import Select from 'react-select';
import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      country:'',
      number:'',
      message:''
    }
    this.onChange = this.onChange.bind(this);
    this.onSelect2 = this.onSelect2.bind(this);
    this.validatePhoneNumber = this.validatePhoneNumber.bind(this);
  }

  onChange(event) {
    this.setState({
      number:event.target.value
    });
    this.validatePhoneNumber('+'+this.state.country+' '+event.target.value);
  }

  onSelect2(cntrObj) {
    this.setState({
      country:cntrObj.value
    });
    this.validatePhoneNumber('+'+cntrObj.value+' '+this.state.number);
  }

  validatePhoneNumber(phoneNumber) {
    /*
    Phone number validation using google-libphonenumber
    */
    let valid = false;
    try {
      const phoneUtil = PhoneNumberUtil.getInstance();
      valid =  phoneUtil.isValidNumber(phoneUtil.parse(phoneNumber));
    } catch(e) {
      valid = false;
    }
    if(valid) {
      this.setState({
        message:'Phone number '+this.getValidNumber(phoneNumber)+' is valid',
        color:'green'
      });
    } else {
      this.setState({
        message:'Phone number '+phoneNumber+' is not valid',
        color:'red'
      });
    }
  }

  getValidNumber(phoneNumber) {
    const phoneUtil = PhoneNumberUtil.getInstance();
    const parsedNumber = phoneUtil.parse(phoneNumber);
    return phoneUtil.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)
  }

  render() {
    return (
      <div>
        <h1>Phone number with country codes using ReactJS</h1>
        <div className="phone-number" style={{display:'flex'}}>
          <div className="phone-number--country">
            <Select value={this.state.country} onChange={this.onSelect2} placeholder="country code"
               options={CallingCodes} labelKey="country" valueKey="value" valueRenderer={(country) => country.value}>
            </Select>
          </div>
          <div className="phone-number--number">
            <FormControl value={this.state.number} onChange={this.onChange} placeholder="phone number">
            </FormControl>
          </div>
        </div>
        <div className="message" style={{color:this.state.color}}>
          {this.state.message}
        </div>
      </div>
    )
  }
}
Read More
This is simple code which can save some of your time, if you trying to build Select field for languages. Find below for complete code

Languages

Find below Languages.js which contains all language names and codes
export default [
    {"value":"English","code":"EN"},
    {"value":"Japanese","code":"JA"},
    {"value":"Afrikaans","code":"AF"},
    {"value":"Albanian","code":"SQ"},
    ......
];

Normal Select Box

This normal select box in which Languages were mapped as options
<select value={this.state.lang} onChange={this.onSelect}>
    {Languages.map((language) => <option value={language.code}>{language.value}</option>)}
</select>

React-bootstrap Select box

This Select box uses bootstrap styles and components
<FormControl value={this.state.lang} onChange={this.onSelect} componentClass="select" placeholder="select">
   {Languages.map((language) => <option value={language.code}>{language.value}</option>)}
</FormControl>

React-select Select box

react-select is React version of Select2. 
<Select value={this.state.lang} onChange={this.onSelect2} placeholder="select"
   options={Languages} labelKey="value" valueKey="code">
</Select>

Complete component code

import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-select/dist/react-select.min.css';
import React from 'react';
import Languages from './Languages';
import {FormControl} from 'react-bootstrap';
import Select from 'react-select';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      lang:'EN'
    }
    this.onSelect = this.onSelect.bind(this);
    this.onSelect2 = this.onSelect2.bind(this);
  }

  onSelect(event) {
    this.setState({
      lang:event.target.value
    });
  }

  onSelect2(language) {
    this.setState({
      lang:language.code
    });
  }

  render() {
    return (
      <div>
        <h1>Select box for languages</h1>
        <select value={this.state.lang} onChange={this.onSelect}>
           {Languages.map((language) => <option value={language.code}>{language.value}</option>)}
        </select>
        <br/><br/><br/>
        <h1>Bootstrap Select box for languages</h1>
        <FormControl value={this.state.lang} onChange={this.onSelect} componentClass="select" placeholder="select">
          {Languages.map((language) => <option value={language.code}>{language.value}</option>)}
        </FormControl>
        <br/><br/><br/>
        <h1>React Select2 for languages</h1>
        <Select value={this.state.lang} onChange={this.onSelect2} placeholder="select"
           options={Languages} labelKey="value" valueKey="code">
        </Select>
      </div>
    )
  }
}
Read More
This is simple code which can save some of your time, if you trying to build Select field for timezones. Find below for complete Timezones code

Timezones

Find below for Timezones.js which contains all timezone names and values
export default [
    {"value":"America/Adak","name":"Adak"},
    {"value":"America/Anchorage","name":"Anchorage"},
    {"value":"America/Anguilla","name":"Anguilla"},
    {"value":"America/Antigua","name":"Antigua"},
    .....
  ];

Normal Select Box

This normal select box in which Timezones were mapped as options
<select value={this.state.timezone} onChange={this.onSelect}>
           {Timezones.map((timezone) => <option value={timezone.value}>{timezone.name}</option>)}
</select>

React-bootstrap Select box

This Select box uses bootstrap styles and components
<FormControl value={this.state.timezone} onChange={this.onSelect} componentClass="select" placeholder="select">
    {Timezones.map((timezone) => <option value={timezone.value}>{timezone.name}</option>)}
</FormControl>

React-select Select box

react-select is React version of Select2. 
<Select value={this.state.timezone} onChange={this.onSelect2} placeholder="select" options={Timezones} labelKey="name" valueKey="value">
</Select>

Complete component code

import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-select/dist/react-select.min.css';
import React from 'react';
import Timezones from './Timezones';
import {FormControl} from 'react-bootstrap';
import Select from 'react-select';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      timezone:'America/Aruba'
    }
    this.onSelect = this.onSelect.bind(this);
    this.onSelect2 = this.onSelect2.bind(this);
  }

  onSelect(event) {
    this.setState({
      timezone:event.target.value
    });
  }

  onSelect2(language) {
    this.setState({
      timezone:language.value
    });
  }

  render() {
    return (
      <div>
        <h1>Select box for Timezones</h1>
        <select value={this.state.timezone} onChange={this.onSelect}>
           {Timezones.map((timezone) => <option value={timezone.value}>{timezone.name}</option>)}
        </select>
        <br/><br/><br/>
        <h1>Bootstrap Select box for Timezones</h1>
        <FormControl value={this.state.timezone} onChange={this.onSelect} componentClass="select" placeholder="select">
          {Timezones.map((timezone) => <option value={timezone.value}>{timezone.name}</option>)}
        </FormControl>
        <br/><br/><br/>
        <h1>React Select2 for Timezones</h1>
        <Select value={this.state.timezone} onChange={this.onSelect2} placeholder="select"
           options={Timezones} labelKey="name" valueKey="value">
        </Select>
      </div>
    )
  }
}
Read More
This Angular Component converts plain text tweets into real tweets. This component is responsible for parsing the tweets and handles transform mention (@sodhanalibrary), hashtags (#AngularJS) and URLs inserted in the tweet in functional URLs. This was created based on jquery-tweet-parser
Source Code           DEMO

Angular Component

This is the Angular Component which you can use it for converting plain text to real tweets
import { Component, Input } from '@angular/core';

@Component({
    selector: 'tweetParser',
    template: `<div [innerHTML]="myHtml"></div>`
})
export class TweetParser {
    @Input('urlClass') urlClass: string = 'react-tweet-parser__url';
    @Input('userClass') userClass: string = 'react-tweet-parser__user';
    @Input('hashtagClass') hashtagClass: string = 'react-tweet-parser__hashTag';
    @Input('target') target: string = '_blank';
    @Input('searchWithHashtags') searchWithHashtags: boolean = true;
    @Input('parseUsers') parseUsers : boolean = true;
    @Input('parseUrls') parseUrls :  boolean = true;
    @Input('parseHashtags') parseHashtags: boolean = true;
    @Input('tweet') tweet: string = '';

    myHtml: string = '';
    constructor() {
    }

    generateLink(url, urlClass, target, text) {
      return `<a href="${url}" className="${urlClass}" target="${target}">${text}</a>`;
    }

    ngOnChanges() {
      this.parseTweet();
    }

    ngOnInit(){
      this.parseTweet();
    }

    parseTweet() {
     const {urlClass, userClass, hashtagClass, target, searchWithHashtags, parseUsers, parseUrls, parseHashtags} = this;

     const REGEX_URL = /(?:\s)(f|ht)tps?:\/\/([^\s\t\r\n<]*[^\s\t\r\n<)*_,\.])/g, //regex for urls
                REGEX_USER = /\B@([a-zA-Z0-9_]+)/g, //regex for @users
                REGEX_HASHTAG = /\B(#[á-úÁ-Úä-üÄ-Üa-zA-Z0-9_]+)/g; //regex for #hashtags
     let searchlink, myTweet = this.tweet; //search link for hashtags
      //Hashtag Search link
     if (searchWithHashtags) {
          //this is the search with hashtag
          searchlink = "https://twitter.com/hashtag/";
      } else {
          //this is a more global search including hashtags and the word itself
          searchlink = "https://twitter.com/search?q=";
      }
      //turn URLS in the tweet into... working urls
      if (parseUrls) {
          myTweet = myTweet.replace(REGEX_URL, (url) => {
              let link = this.generateLink(url, urlClass, target, url);
              return url.replace(url, link);
          });
      }
      //turn @users in the myTweet into... working urls
      if (parseUsers) {
          myTweet = myTweet.replace(REGEX_USER, (user) => {
              let userOnly = user.slice(1),
                  url = `http://twitter.com/${userOnly}`,
                  link = this.generateLink(url, userClass, target, user);
              return user.replace(user, link);
          });
      }
      //turn #hashtags in the myTweet into... working urls
      if (parseHashtags) {
          myTweet = myTweet.replace(REGEX_HASHTAG, (hashtag) => {
              let hashtagOnly = hashtag.slice(1),
                  url = searchlink + hashtagOnly,
                  link = this.generateLink(url, hashtagClass, target, hashtag);
              return hashtag.replace(hashtag, link);
          });
      }

      this.myHtml  = myTweet;
   }
}

Usage

<tweetParser [tweet]="myTweet" urlClass="myUrlClass"></tweetParser>
Read More

Blogroll

Popular Posts