A Simple ReactJS Form Example

In this tutorial, we will learn how to use forms in React.

In HTML, Form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

input tag

In React, A input set the value using {this.state.value} and change handle by onChange event.

<input type=”text” name=”name” value={this.state.value} onChange={this.handleChange} />

checkbox tag

In React, checkbox input is checked or unchecked handle by attribute checked. On check or uncheck the event called and set the value true if checked and false if unchecked.

<label>
      <input type=”checkbox” checked={this.state.isConfirm} onChange={this.handleInputChange} />Please check to confirm:
</label>

textarea tag

In React, A textarea uses a value attribute, so textarea element in React is slightly different from ordinary HTML.

<label>
   Comment :
   <textarea name=”comment” value={this.state.value} onChange={this.handleChange} />
</label>

select tag

In HTML, select input creates a drop-down list and make selected to show the value as selected for drop-down values. In React, instead of using selected attribute, it uses a value attribute on the root select tag.

<label>
   Pick your favorite flavor:
   <select name=”flavor” value={this.state.value} onChange={this.handleChange}>
         <option value=””>–Pick your favorite flavor–</option>
         <option value=”grapefruit”>Grapefruit</option>
         <option value=”lime”>Lime</option>
         <option value=”coconut”>Coconut</option>
         <option value=”mango”>Mango</option>
   </select>
</label>

file input tag

In React, An <input type=”file” /> is always an uncontrolled component because its value can only be set by a user, and not programmatically. You should use the File API to interact with the files.

<label>
   Document Upload
   <input type=”file” name=”fileUpload” onChange={this.fileHandler} />
</label>

ReactJS Form Example

In the following example, we will set an input value using state value = {this.state.data}. onChange allows to update the state whenever the input value changes. And When you submit the form we apply the onSubmit event and restrict page to reload using event.preventDefault();

import React, {Component} from ‘react’;
import ‘./App.css’
class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         isConfirm: false,
         fileUpload : ”
      };
      this.handleInputChange = this.handleInputChange.bind(this);
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   }

   fileHandler = event => {
      this.setState({
      fileUpload : event.target.files[0]
      });
   }

   handleInputChange(event) {
      const target = event.target;
      const value = target.type === ‘checkbox’ ? target.checked : target.value;
      this.setState({
         isConfirm: value
      });
   }

   handleChange(event) {
      this.setState({[event.target.name]: event.target.value});
   }

   handleSubmit(event) {
      event.preventDefault();
      let htm = ‘<h2>O/p</h2>A name was submitted : <strong>’ + this.state.name +'</strong> <br/ >’+
‘A comment was submitted : <strong>’ + this.state.comment +'</strong> <br/ >’+
‘A Confirm selected : <strong>’ + this.state.isConfirm +'</strong> <br/ >’+
‘Your favorite flavor : <strong>’ + this.state.flavor +'</strong> <br/ >’+
‘Your file Upload : <strong>’ + this.state.fileUpload.name+'</strong>’;

      document.getElementById(‘dataSubmit’).innerHTML = htm;
   }

   render(){
      return (
      <div className=”App”>
      <form enctype=”multipart/form-data” method=”post” onSubmit={this.handleSubmit}>

      <div>
         <label>
            Name : <input type=”text” name=”name” value={this.state.value} onChange={this.handleChange} />
         </label>
      </div>

      <div>
         <label>
            Comment :
         <textarea name=”comment” value={this.state.value} onChange={this.handleChange} />
         </label>
      </div>

      <div>
         <label>
            <input type=”checkbox” checked={this.state.isConfirm} onChange={this.handleInputChange} />
      Please check to confirm:
         </label>
      </div>

      <div>
         <label>
            Pick your favorite flavor:
            <select name=”flavor” value={this.state.value} onChange={this.handleChange}>
               <option value=””>–Pick your favorite flavor–</option>
               <option value=”grapefruit”>Grapefruit</option>
               <option value=”lime”>Lime</option>
               <option value=”coconut”>Coconut</option>
               <option value=”mango”>Mango</option>
            </select>
         </label>
      </div>

      <div>
         <label>
            Document Upload
            <input type=”file” name=”fileUpload” onChange={this.fileHandler} />
         </label>
      </div>

      <input type=”submit” value=”Submit” />

      </form>
      <div id=”dataSubmit”></div>

      </div>
      );
      }
}
export default App;

Output

List of important custom and in-built AMP tags

amp-img

amp-img is use as replacment of HTML img tag. amp-img tag effectively manage image resource at runtime. It uses lazy load to reduce page load time.

To use amp-img need to specify width and height, src attriburtes. It also support three optional attributes srcset, alt, attribution.

  • src – url of image need to display.
  • srcset – for retine ready images. We can provide different image for devices varying pixel ratio.
  • attribution – to set attribution text of the image.

To set image to responsive use layout attribute and set it value responsive.

Example of amp-img
<amp-img src="/img/amp.jpg"
srcset="/img/amp.jpg 1080w, /img/amp-900.jpg 900w, /img/amp-800.jpg 800w,
/img/amp-700.jpg 700w, /img/amp-600.jpg 600w, /img/amp-500.jpg 500w, /img/amp-400.jpg 400w,
/img/amp-300.jpg 300w, /img/amp-200.jpg 200w, /img/amp-100.jpg 100w"
width="1080"
height="610"
layout="responsive"
alt="an image"></amp-img>

amp-img is builtin tag and imported via the AMP js.

amp-video

amp-video is replacement of Html Video tag. It also lazy load video at runtime.

To use amp-video you must specify width, height and src attributes. It also support some more optional attributes poster, autoplay, controls, loop, muted. It also accept three unique HTML child nodes tag, placeholder before video start, and fallback.

Example of amp-video
<amp-video width=400 height=300 src="https://yourhost.com/videos/myvideo.mp4"
    poster="myvideo-poster.jpg">
  <div fallback>
    <p>Your browser doesn’t support HTML5 video</p>
  </div>
  <source type="video/mp4" src="foo.mp4">
  <source type="video/webm" src="foo.webm">
</amp-video>

amp-video is in-builtn tag and imported via the AMP js.

amp-audio

amp-audio is replacement of HTML audio tag. It is use to embed audio file in amp pages.

To use amp-audio you must specify src, width and height attributes, amp-audio also have three more optional attribute autoplay, loop and muted.

  • src – audio file url.
  • autoplay – It will autoplay animated image.
  • loop – it will auto loop audio.
  • muted – muted audio by default.
Example of amp-audio
 <amp-audio width="400" height="300" src="https://yourhost.com/audios/myaudio.mp3">
  <div fallback>
    <p>Your browser doesn’t support HTML5 audio</p>
  </div>
  <source type="audio/mpeg" src="foo.mp3">
  <source type="audio/ogg" src="foo.ogg">
</amp-audio>

To use amp-audio you have to include below script in <head> section

 <script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>

amp-accordion

amp-accordion is use to implement accordion in amp pages. Accordion is mostly use in faq pages.

Amp-accordion can have one or more first child node <section> and each <section>contain 2 child node first one is heading and second node is content and clicking heading it will toggle display of content.

Below example of amp-accordion
 <amp-accordion>
  <section expanded>
    <h2>Section 1</h2>
    <p>Bunch of awesome content</p>
  </section>
  <section>
    <h2>Section 2</h2>
    <div>Bunch of awesome content</div>
  </section>
  <section>
    <h2>Section 3</h2>
    <amp-img src="/awesome.png" width="300" height="300"></amp-img>
  </section>
</amp-accordion>

amp-accordion also provides below attributes

  • disable-session-states – to disable preserving the collapsed/expanded state of the amp-accordion element
  • expanded – to set on any <section> expanded on page load.

To use amp-accordion you have to include below script in <head> section

<script async custom-element="amp-accordion" src="https://cdn.ampproject.org/v0/amp-accordion-0.1.js"></script>

amp-carousel

amp-carousel tag to display content boxes horizontally. A carousel is set of number of items with optional navigational arrow. The carousel move items if user swipe, or use arrow key or use navigation arrow.

To use amp-carousel you must specify height attribute, it also provide more optional attributes controls, type, loop, autoplay, delay.

  • controls – to display navigation arrow
  • type – by default its value is carousel all slides are shown and scrollable. If type value is Slides, it will display singe silde at a time. With type slides you can use three more attribute loop, autoplay, delay.
Example of carousel
 <amp-carousel width=300 height=400>
  <amp-img src="my-img1.png" width=300 height=400></amp-img>
  <amp-img src="my-img2.png" width=300 height=400></amp-img>
  <amp-img src="my-img3.png" width=300 height=400></amp-img>
</amp-carousel>

To use amp-audio you have to include below script in <head> section

<script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script>

amp-lightbox

amp-lightbox tag to implement light box interface. amp-lightbox will have to define child node
to display child node content in lightbox on tap or click event.

Example of amp-lightbox
 <button on="tap:my-lightbox">Open lightbox</button>
<amp-lightbox id="my-lightbox" layout="nodisplay">
  <div class="lightbox">
    <amp-img src="my-full-image.jpg" width=300 height=800 on="tap:my-lightbox.close">
  </div>
</amp-lightbox>

To use amp-lightbox you have to include below script in <head> section

<script async custom-element="amp-lightbox" src="https://cdn.ampproject.org/v0/amp-lightbox-0.1.js"></script>

amp-ad/amp-embed

amp-ad is use to display ads. amp-embed is an alias of the amp-ad and use amp-embed when logically more accurate. Your ad javascript will not run inside your amp page, AMP will loads an iframe on runtime and execute ad javascript inside iframe sandbox.

To use amp-ad you need to specify type, width, height attributes. Type is name of ad network to which your ad belong. All data-* attributes also depend on type of network.

Below example amp-ad of for different type of network

 <amp-ad width=300 height=250
    type="a9"
    data-aax_size="300x250"
    data-aax_pubname="test123"
    data-aax_src="302">
</amp-ad>

<amp-ad width=320 height=140
    type="colombia"
    layout=responsive
    data-clmb_slot="129883"
    data-clmb_position="1"
    data-clmb_section="0">
</amp-ad>

<amp-embed width=400 height=300
    type="taboola"
    layout=responsive
    data-publisher=thepublisher
    data-mode=themode
    data-article=auto
    data-placement="Below Article Thumbnails">
</amp-embed>

To use amp-ad you have to include below script in <head> section

<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>

amp-analytics

amp-analytics is use to collect analytics data from an AMP page. Currently amp-analytics support below events:

  • Pageview
  • Anchor Clicks
  • Timer
  • Scrolling
  • AMP Carousel changes

To send data to analytcis server you need to specify json configuration object inside amp-analytics tag. Some vendor provide pre configure json configuration object. With type attribute you can set vendor and their json object.

Example for amp-analytics
<amp-analytics type=”abc”>
<script type="application/json">
{
 .........
}
</script>
</amp-analytics>

To use amp-analytics you have to include below script in <head> section

<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>

amp-iframe

amp-iframe to display an iframe in AMP pages. amp-iframe is more secure than html <iframe> tag.

To use amp-iframe you must follow these rules iframe must be at least 600px or 75% of the first viewport away from the top and can only request resources via HTTPS.

Example for amp-iframe
 <amp-iframe width="500"
      height="281"
      layout="responsive"
      sandbox="allow-scripts allow-same-origin allow-popups"
      allowfullscreen
      frameborder="0"
      src="https://player.vimeo.com/video/140261016">
  </amp-iframe>

To include an amp-iframe, first include the following script to the <head>

<script async custom-element="amp-iframe"
  src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>

Amp also provide some more tags that we can use when require <amp-selector>, <amp-sidebar>,<amp-facebook>,<amp-instagram>,<amp-pinterest>,<amp-playbuzz>,<amp-twitter>,<amp-vine>,<amp-form>,<amp-font>,<amp-dynamic-css-classes>,<amp-anim>,<amp-app-banner> and more you can refer it on amp officia site.

Note: Also check AMP page example code

AMP (Accelerated Mobile Pages) Example Pages

AMP (Accelerated Mobile Pages) is a Google open source project to speed up page load in mobile devices.

AMP consist of three main parts

  • AMP HTML is HTML with custom AMP tags, properties and some restrictions like only subset of css and html are not allowed that slow down page loading. Only valid AMP HTML files will be shown in Google Search.
  • AMP JS library manage resource loading, provide custom tags, load external resources asynchronously so external resources should not block page rendering, pre-calculate layout of every element before any resources are loaded and it also disable slow CSS selectors.
  • Google AMP CACHE is a content delivery network. It fetches valid AMP HTML pages and cache them to improve page performance.

Sample AMP html

<!doctype html>
<html amp lang="en">
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<title>Hello, AMPs</title>
<link rel="canonical" href="http://example.ampproject.org/article-metadata.html" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "NewsArticle",
"headline": "Open-source framework for publishing content",
"datePublished": "2015-10-07T12:02:41Z",
"image": [
"logo.jpg"
]
}
</script>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
</head>
<body>
<h1>Welcome to the mobile web</h1>
</body>
</html>

Required markup for AMP HTML document

  • Start your document with the doctype <!doctype html>.
  • Below doctype <html > tag (<html amp> is accepted as well).
  • Require <head> and <body> tags
  • First tag after <head> is <meta charset=”utf-8″>
  • Include a <script async src=”https://cdn.ampproject.org/v0.js”></script> tag as the second child of their <head> tag (this includes and loads the AMP JS library).
  • <link rel=”canonical” href=”$SOME_URL” /> tag inside their <head> tag that points to the regular HTML version of the AMP HTML document or to itself if no such HTML version exists.
  • Add a <meta name=”viewport” content=”width=device-width,minimum-scale=1″> tag inside their <head> tag. It’s also recommended to include initial-scale=1.
  • Add the following in <head> tag:
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>

Optional meta-data

A schema.org definition in above sample code is optional. However you can use it, if you want to distribute your content in some places like google search news top stories, rich cards, critic review cards according to your content type.

Validation

As we learn about required syntax need to follow , when you create AMP web page make sure that is valid AMP. It should display correctly to mobile devices to users. You can validate your AMP pages at https://search.google.com/search-console/amp.

Link AMP and non AMP pages

To make sure that search engines read (index) your we pages correctly. You need to add canonical link.

On normal web page –

<link rel="amphtml" href="amp-page-url" />

On AMP web page –

<link rel="canonical" href="none-amp-page-url" />

Demo

Non Amp page: https://sisnolabs.com/demo-non-amp.html
Amp Page: https://sisnolabs.com/demo-amp.html

Improved loading performance

Page load time, http request, page size all almost improved by more than 50%.

Note: In our next post we will going to write about AMP built-in and custom tags.

Canvas Examples – Add Text | Add Image | Resize Image | Change Canvas Color

How to add text to Canvas?

For add text we can do that using fillText(‘text’, x, y) or strokeText(“text”, x, y) method. The text is rendered using the current stroke or fill style, which can be a color, gradient, or pattern. You can specify a number of text settings, such as the font family, size, and weight, and the text alignment and baseline.

 

The textBaseline attribute’s keywords which correspond to the alignment points in the font, where:

  • top corresponds to the top of the em square
  • hanging is the hanging baseline
  • middle is the middle of the em square
  • alphabetic is the alphabetic baseline
  • ideographic is the ideographic baseline
  • bottom corresponds to the bottom of the em square

 

Here is example for add text with gradient, font family, size, weight, shadow.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

context.font=”italic 30px Georgia”;

context.strokeStyle = “rgba(237,229,0,1)”;

context.shadowOffsetX = 2;

context.shadowOffsetY = 2;

context.shadowBlur = 1;

context.shadowColor = “rgba(0,0,0,1)”;

var gradient = context.createLinearGradient(200,70,200,110);

gradient.addColorStop(0, “#f55b5b”);

gradient.addColorStop(1, “#3112a3”);

context.fillStyle = gradient;

context.fillText(“Hello World”, x, y);

 

How to add image to Canvas?

 

To draw an image using HTML5 Canvas, we can use the drawImage() method which requires an image object and a destination point. The destination point is relative to the top left corner of the image.

 

The drawImage function includes three parameters and is expressed in the form drawImage(object image, float x, float y). The image file formats supported within the canvas element and drawImage function are .jpg, .gif, and .png.

 

The drawImage() method requires an image object, we must first create an image and wait for it to load before instantiating drawImage(). We can do this by using the onload property of the image object.

 

Here is example for add image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10);

}

imgObj.src = “image/nature.jpg”;

 

How to resize image?

Now we have drawImage() method for draw image on Canvas, for resize image we can use same method with optional height and width parameters and is expressed in the form drawImage(object image, float x, float y, [optional width], [optional height]).

 

Here is example for add and resize image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10, 200, 100);

}

imgObj.src = “image/nature.jpg”;

 

 

Canvas Examples – Draw Line | Rectangle | Circle | Undo

Canvas Examples – Draw Line | Rectangle | Circle | Undo

What is Canvas?

Canvas is an HTML5 element which can be used to draw graphics using scripting (usually JavaScript).

We’ll need to place the canvas tag somewhere inside the HTML document, access the canvas tag with JavaScript, create a context, and then utilize the HTML5 Canvas API to draw visualizations. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the canvas element.

 

Add Canvas to HTML

A canvas is a rectangular area on an HTML page, and it is specified with the canvas element.

<canvas id=”myCanvas” width=”200″ height=”100″></canvas>

Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas

 

Draw Line to Canvas

To draw a line using HTML5 Canvas, we can use the beginPath(), moveTo(), lineTo(), and stroke() methods.

First, we can use the beginPath() method to declare that we are about to draw a new path. Next, we can use the moveTo() method to position the context point (i.e. drawing cursor), and then use the lineTo() method to draw a straight line from the starting position to a new position. Finally, to make the line visible, we can apply a stroke to the line using stroke().

 

Example for line draw

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.moveTo(x, y);

context.lineTo(x, y);

context.stroke();

Draw Rectangle On Canvas

To create a rectangle using HTML5 Canvas, we can use rect(x,y,w,h) method, and for rectangle visible use stroke() method.

The rect() method have four parameter ie “x, y, width, height”, x is the upper left x co-ordinate, y is the upper left y co-ordinate of rectangle, then width of rectangle and height of rectangle.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.rect(x, y, w, h);

context.stroke();

 

strokeRect(x,y,w,h) and fillRect(x,y,w,h) also use for draw rectangle, strokeRect() method done same as rect() and stroke() method. And fillRect() method use to draw rectangle with fill color. If you are not use fillStyle property then fillRect method draw rectangle with default black color.

 

context.fillStyle= “#ff00ff”;

context.fillRect(x, y, w, h);

OR

context.fillStyle= “rgb(255, 0, 255)”;

context.fillRect(x, y, w, h);

Also we can clear the canvas with clearRect(x,y,w,h) method.

context.clearRect(0, 0, canvas.width, canvas.height);
Draw Circle On Canvas

To draw a circle with HTML5 Canvas, we can use arc() method. and for circle visible use stroke() method.

Arcs are defined by a center point ie (x,y), a radius, a starting angle, an ending angle, and the drawing direction (either clockwise or anticlockwise, true for clockwise and false for anticlockwise, default is true;).

 

For draw full arc we can use starting angle is 0 and ending angle is 2* PI.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.arc(x, y, r, 0, 2*Math.PI);

context.stroke();

 

We can styled circle with fillStyle, strokeStyle and lineWidth properties.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.arc(x, y, r, 0, 2*Math.PI);

context.fillStyle = ‘#DA2C35’;

context.fill();

context.lineWidth = 3;

context.strokeStyle = ‘#003300’;

context.stroke();

Undo

There is not much we have to do add undo functionality to a Canvas application. We can achieve that by saving the state after each event in an array. These are simple JavaScript arrays where we are storing the images using push() and pop() methods. The canvas image is retrieved using the context.toDataURL(“image/png”) method and when we undo. we take that image and paint it again on the canvas after clearing the current canvas.

 

Saving Canvas state.

var restorePoints = [];

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

var imgSrc = canvas.toDataURL(“image/png”);

restorePoints.push(imgSrc);

 

Repaint Canvas

var oImg = new Image();

oImg.onload = function() {

var canvas = document.getElementById(“myCanvas”);
var canvasContext = canvas.getContext(“2d”);
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.drawImage(oImg, 0, 0);
}

oImg.src = restorePoints.pop();