Create Higher Order Components in React

Create Higher Order Components in React

Higher Order Components (HOCs) are the coined term for a custom Component that accepts dynamically provided children. For example, let’s make <LazyLoad /> Component that takes child image tags as children, waits until the <LazyLoad /> Component is scrolled into view, and then loads the images they point to in the background (before rendering them to the DOM).

An HOC accepts children via props:

DOM.render(
    <LazyLoad>
        <img src="../media/1.gif"/>
        <img src="../media/2.gif"/>
        <img src="../media/3/gif" />
    </LazyLoad>,
    document.body)

Creating an HOC means handling this.props.children in the Component’s code:

class LazyLoad extends Component {
    constructor(p){
        super(p)
        this.state = { loaded:0 }
        this._scroll = this._scroll.bind(this)
    }
    _scroll(){
        let el = DOM.findDOMNode(this)
        let {top} = el.getBoundingClientRect()
        let viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
        if(top < (viewportHeight + this.props.top)) {
            window.removeEventListener('scroll', this._scroll)
            this.setState({loaded:1})
        }
    }
    componentDidMount(){
        window.addEventListener('scroll', this._trackYPosition)
        this._scroll()
    }
    componentWillUnmount(){
        window.removeEventListener('scroll', this._trackYPosition)
    }
    render(){
        let {children} = this.props,
            {loaded} = this.state
        return <div>
            {loaded && children}
        </div>
    }
}

LazyLoad.defaultProps = {
    top: 100
}

Noting a few things about this code:

  1. We set up initial state (this.state = {loaded: 0}) in the constructor(). This will be set to 1 when the parent container is scrolled into view.
  2. The render() returns the props.children as child elements when this occurs. Extract the src by using ES6 destructuring, where {props:{src}} creates a variable src with the appropriate value.
  3. We used a single componentDidMount() lifecycle method. This is used because on mount, we’d like the component to check if the HOC is visible.
  4. The largest function of our component, _scroll(), grabs the HOC Component’s DOM element with DOM.findDOMNode() and then gets the elements position. This position is compared to the height of the browser window, and if it is less than 100px from the bottom, then the scroll listener is removed and loaded is set to 1.

This technique is called HOC (Higher Order Component) because we pass in elements as this.props.children when we nest those elements inside the container component:

<HOC>
    <div>some</div>
    <span>children</span>
    <Props/>
</HOC>

All of these nested elements (which can be custom components) are nested under <HOC/>, thus HOC’s code will be able to access them as this.props.children.

Build a SEO-friendly React blog with an API-based CMS

Build a SEO-friendly React blog with an API-based CMS

Have you ever wanted to build a server-rendered, SEO-friendly website using React and Node.js? The typical solutions for achieving this are either using a pre-rendering service like Prerender.io, or implementing server-side rendering of React components.

A relatively new alternative is Next.js, a framework for building universal React webapps. Next.js provides out-of-the-box tools for server-side rendering including setting HTML tags for SEO and fetching data before rendering components. Read more about the philosophy behind Next.js here.

In this Blog, I’m going to show you how to build a CMS-powered blog using React, Next.js, and ButterCMS.

ButterCMS is an API-based CMS and content API. You can think of Butter as similar to WordPress except that you build your website in your language of choice and then plug-in the dynamic content using an API. You can try ButterCMS for yourself by signing in with Github.

Getting Started

Create a new directory for your app and add a package.json file:

{
  "name": "react-blog"
}

Install Next.js and React. As of the time of this writing, we’ll want to install the Next.js so we can setup dynamic routes later:

npm install next@beta react react-dom --save

Then add a script to your package.json:

{
  "scripts": {
    "start": "next"
  }
}

Next.js treats every js file in the ./pages directory as a page. Let’s setup a basic homepage by creating a ./pages/index.js inside your project:

export default () => (
  <div>My blog homepage</div>
)

And then just run npm run start and go to http://localhost:3000.

Finally, create a ./pages/post.js and make sure it loads at http://localhost:3000/post:

export default () => (
  <div>A blog post</div>
)

Fetching blog posts

Next we’ll integrate ButterCMS so we can fetch and render blog posts dynamically.

First install the ButterCMS Node.js API client and restart your server:

npm install buttercms --save

We’ll update index.js to be a React component that fetches and displays posts using the ButterCMS SDK:

import React from 'react'
import Link from 'next/link'
import Butter from 'buttercms'

const butter = Butter('de55d3f93789d4c5c26fb07445b680e8bca843bd')

export default class extends React.Component {
  static async getInitialProps({ query }) {
    let page = query.page || 1;

    const resp = await butter.post.list({page: page, page_size: 10})    
    return resp.data;
  }
  render() {
    const { next_page, previous_page } = this.props.meta;

    return (
      <div>
        {this.props.data.map((post) => {
          return (
            <div>
              <a href={`/post/${post.slug}`}>{post.title}</a>
            </div>
          )
        })}

        <br />

        <div>
          {previous_page && <Link href={`/?page=${previous_page}`}><a>Prev</a></Link>}

          {next_page && <Link href={`/?page=${next_page}`}><a>Next</a></Link>}
        </div>
      </div>
    )
  }
}

With Next.js getInitialProps will execute on the server on initial page loads, and then on the client when navigating to a different routes using the built-in <Link> component. getInitialProps also receives a context object with various properties – we access the query property for handling pagination. We are fetching posts from a ButterCMS test account – sign in with Github to setup your own posts.

In our render() method we use some clever syntax to only display pagination links only when they’re applicable. Our post links will take us to a 404 – we’ll get these working next.

Displaying posts

To get our post links working we need to setup dynamic routing for our blog posts. Create a custom server ./server.js that routes all /post/:slug URLs to our post component:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname.includes('/post/')) {
      const splitPath = pathname.split("/");

      // Add post slug to query object
      query.slug = splitPath[2];

      app.render(req, res, '/post', query)
    } else {
      handle(req, res, parsedUrl)
    }
  })
  .listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

We’ll also update our post component to fetch blog posts via slug and render the title and body:

import React from 'react'
import Butter from 'buttercms'

const butter = Butter('de55d3f93789d4c5c26fb07445b680e8bca843bd')

export default class extends React.Component {
  static async getInitialProps({ query }) {
    const resp = await butter.post.retrieve(query.slug);  
    return resp.data;
  }
  render() {
    const post = this.props.data;

    return (
      <div>
        <h1>{post.title}</h1>
        <div dangerouslySetInnerHTML={{__html: post.body}} />
      </div>
    )
  }
}

Finally, update our package.json start script to use our customer server and restart:

"scripts": {
  "start": "node server.js"
}

SEO

Next.js provides a <Head> component for setting HTML titles and meta tags. Add import Head from 'next/head' to the top of ./pages/post.js and use the component in the render() method:

render() {
  const post = this.props.data;

  return (
    <div>
      <Head>
        <title>{post.seo_title}</title>
        <meta name="description" content={post.meta_description} />
        <meta name="og:image" content={post.featured_image} />
      </Head>

      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{__html: post.body}} />
    </div>
  )
}

Restart the server and inspect the HTML source of a post to verify that tags are getting set correctly.

Wrap Up

Next.js is a powerful framework that makes it easy to build universal React apps. With ButterCMS you can quickly build CMS-powered blogs and websites with React.

Be sure to check out ButterCMS, a hosted API-based CMS and content APIand blog engine that lets you build CMS-powered apps using any programming language including Ruby, Rails, Node.js.NET, Python, Phoenix, Django, React, Angular, Go, PHP, Laravel, Elixir, and Meteor.

Code Source: available on Github.

“Hello ReactJS” – Let’s Start with React JS

Screen Shot 2017-02-15 at 9.33.43 PM

We already know ReactJS is for frontend development. React JS is not a framework, it is just a Library. We use ReactJC for creating User Interfaces (UI). It renders your UI and responds to the events. In simple language it is just the ‘V’ of MVC.

Here are some differences between Angular and React JS:

  • Angular is actually a framework whereas React is a library.
  • Choosing between Angular and React is like choosing between buying an off-the-shelf computer and building your own with off-the-shelf parts.
  • Angular means conforming to its structure, its view on how your application should be architected and very often its choice of internal components such as routing, http services etc. With React you’re very much free to choose your own internal components and your own application architecture. This is why there are so many ‘starter kits’ that bundle react with a bunch of other off the shelf components and frameworks such as Flux, Reflux, Redux etc.
  • Depending on your project this is a blessing or a curse, with Angular you know that you can get off the ground quickly and other Angular developers are going to be able to join your team and contribute very quickly. With React you might have to spend time bringing new team members up to speed on whatever architecture decisions the project started with, and the choice of components is a minefield of immature components or incompatibilities.

So after reading this you can decide, which one you should chose?

In my experiences it also have many other benefits like:

  1. Modularity and Reusability of Codebase
  2. Productivity
  3. SEO
  4. Performance
  5. debugging

It helps in above things and Increase your productivity.

Before starting with React you should have knowledge of basic things:

  • HTML
  • Basic Javascript
  • CSS
  • How to write CODE
  • Webpack

And Your machine should have:

  • Node JS
  • Any Programming tool – IDE, Sublime –

Here we build components not templates, So same components can be used in many other templates using simple logics. Data can come from anywhere. One more thing you shold know before starting – JSX,  So JSX allows you to write JS & XML together. Re-render of components takes place:

  • Every component has “state” and “props”.
  • Acts as an “Immutable DOM”.
  • Re-render the whole app once the state changes.

Let’s write “Hello ReactJS”.

Steps:

  1. Open terminal.
  2. Create a folder: mkdir reactJSScreen Shot 2017-02-15 at 7.24.34 PM
  3.  Go inside the folder: Screen Shot 2017-02-15 at 7.24.50 PM
  4. Now install npm, here I’m assuming your system already has, latest version of NodeJS: Use command- npm init: Screen Shot 2017-02-15 at 7.33.39 PMSo in above command, when you will write- npm init for node package manager installing, it will ask few questions- like Name , description, Author and licence. Fill these fields and other fields may leave vacant.
  5. Now you should install all the dependencies. First we focus on production dependencies and then deployment dependencies, which will be useful in Deployment time. Use Command:npm install react react-dom –saveThese are production dependencies. It will take some time. –save is telling us- this is for production dependencies.Screen Shot 2017-02-15 at 8.28.10 PM

     

  6. Now we’ll go for development dependencies. Write command: npm install webpack webpack-dev-server babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-2 –save
    1. We need some server side functionality for this because this is not a simple HTML file which can be opened by double click on browser, so for this we need to do something on server side.
    2. After running above command for deployment dependencies, we’ll some additional dependencies here: Screen Shot 2017-02-15 at 8.33.59 PM
  7. Now created a simple src folder, src/App – App folder then src/index.html ! Note- here we are creating index.html. just for our fist App. In react no HTML. We use JSX only.in index.html file make HTML5 skeltan. And create a file named – config.jsHere I am not telling abour webpack, Just sharinf the webpack file which have all the dependencies: Screen Shot 2017-02-15 at 8.53.46 PM
  8.  So after creating webpack, Created a index.js file inside the App folder and this will so as result. For now I am just priting :console.log (“hello ReactJS”);
  9. Then I have to set the path for server side, where the result will show up: So in package.json I deleted : “test”: “echo \”Error: no test specified\” && exit 1″, And written the Start command for server side: Screen Shot 2017-02-15 at 9.01.24 PM
  10. So after building the start and build dependencies our Code is ready to run with npm run start: Screen Shot 2017-02-15 at 9.11.23 PM
  11. So here http://localhost:8080/ is local address to run our App.So here we can see out Output in console: Screen Shot 2017-02-15 at 9.13.38 PM

    Hello ReactJS 

    I have used many new thigs here so you can just ask the question related to thos things. Comment Below. Thanks. Code Code Code. 🙂 

Better Understanding of Angular JS, React JS and Node JS

danguu

We all know we are in next generation of JavaScript, where we are getting everything customized as per user requirements. For the same thing we have Angular JS, React JR and Node JS. These are three most useful programming language of current years. Here is  the overview of Angular JS, React JS and Node JS:

screen-shot-2016-11-27-at-5-15-15-pm

Here is the description of all three new technologies.

 

Angular JS: Some of Angular Devs developed Angular JS with the primary purpose of addressing single page application creation challenges. Angular JS simply works with MVC platform, where it simplifies development by providing a reliable. Angular JS follow some guidelines, like- Angular data binding In Angular JS, the model and the view are linked to allow automatic data synchronization between the two.

In angular JS Any changes to the view are instantly propagated on to the model and vice versa. This property makes Angular app development less demanding as the programming model is simplified for the coder. Angular modular development Building modular rich client-side applications that are well structured is now possible with Angular. Modules are created in separate Js files and are essential in the separation of logic. They play a vital role of keeping the code organized. Examples of Angular Js modules include controllers, applications, and services. Every part of the application is kept in a separate container to keep the code clean.

Let’s discuss with an Example (Create an expression in Angular):

 

<html>

         <head>

         <script src=” https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js”>

         </script>

         </head>

         <body>

                  <div ng-app>

                  <p> Expression {{10+10}} </p>

                  </div>

         </body>

</html>

 

Angular code creates a module. Here we can define

Here we can define <div ng-app=”myApp”> … </div>

And can add script: var app = angular.module(“myApp”, []);

For More Visit: https://angularjs.org/

 

React JS: Again a revolutionary platform, it provides us high-performance client and server side rendering with a one-way flow for data binding, This is my favorite technology. When I work on this feel like flying in sky. React JS is based on building reusable components of code base which makes app very light weight, more of a library, which makes it quite easy to work with. I think React is more of a library than a framework. It can best be described as an application view that allows the programmer to utilize reusable components again and again. It is composed of its own React libraries, tools, and solutions that developers can use to build their own JS framework.

See the code:

1

See the benefits in above table and Read more, know more about react JS :

https://facebook.github.io/react/

 

Node JS: This is the platform, where I’ve not worked a lot, but this is the time when I am learning Node JS. It is a JS run time platform powered by Google chrome V8 Javascript engine. Node JS can be described as Javascript that has been given the ability to run on the computer, instead of the browser, like normal JS. This is made possible by the V8 JavaScript run time engine.

Based on a module architecture, Node simplifies the development of complex applications. It is works on an event-driven non-blocking IO model and is adapted for developing server side applications in JavaScript. It allows you to build Utilities that you can concatenate and create JavaScript files with on your machine.

See the code:

 screen-shot-2016-11-27-at-5-45-44-pm

See the benefits of Node JS in above list, Also read more know more abote Node:

https://nodejs.org/en/

So there are 3 different tools, bound by their common dependence on Javascript. Start working with these tools and learn As much as you can.

React – Redux Overview

redux-intro

Philosophy of React is very simple. UI is most predictable when it’s the pure function of state. React solves this problem. UI = f (state)

And Redux is the data/state management library. Redux attempts to make state mutations predictable by imposing certain restrictions on how and when state updates can happen.

This week I am learning Redux, just sharing few of my learnings. We use redus for JS apps. Redux helps us to write applications which behave consistently, run in different environments (client, server, and native), and they are very easy to test. I am also learning react and I read We can use Redux apps with React, Angular OR jQuery. Also, Redux works especially well with libraries like React because it let you describe UI as a function of state, and Redux emits state updates in response to actions.

Redux asks you to:

  • Describe application state as plain objects and arrays.
  • Describe changes in the system as plain objects.
  • Describe the logic for handling changes as pure functions.

Redux works with three simple principles:

  1. Store: Single source of truth – The state of your whole application is stored in an object tree within a single.
  2. Action: State is read-only – The only way to mutate the state is to dispatch an action, an object describing what happened
  3. Reducer: Changes are made with pure functions – To specify how the state tree is transformed by actions, you write

How to Install Redux:

Just write-  //   npm install –save redux  //

Use NPM here package manager.

Most likely, you’ll also need the React bindings and the developer tools.

 npm install –save react-redux npm

install –save-dev redux-devtools

In react It works in flow:

STORE –> Action –> Reducer –> VIEW

 Just write-

npm install –save redux

Use NPM here package manager.

Redux has many elegantly designed features, and compared to Fluxxor you can write a lot less repetitive code and logic. Out of all features, I like Redux’s Action the most. After reading the source code for Action, I realized there are a lot of functional programming concepts in the code.

Sharing the Example code of Redux+ React App:

screen-shot-2016-10-13-at-2-19-50-am

In the code above, we can see the App component App is wrapped inside the Provider component, and this Provider component uses a prop to point us to the app’s state:

screen-shot-2016-10-13-at-2-22-43-am

{ todos: state.todos };

Then use:

export function addTodo(text) {

return { type: types.ADD_TODO, text };

}

 

However, through a connect function, our App component will obtain a this.props.action.addTodo, and this function dispatches the original action creator that was returned by an action object. dispatch(ActionCreators.addTodo(…)).

 It is just learning overview, stay tune for next descriptive blog.

React to Native React

I hope you have already done enough with ReactJS. Now its time to work with Native React. When native react was launched response was super awesome and positive. This is the revolution for Mobile web world. Internet says it was launched on March 2015, so just a very new technology. As we know a country can not be built in a day, similarly it applies to programming language. It takes some time to be mature.

When we talk about mobile technologies, two name comes in mind- Cordova and Phonegap. But now they have some drawback. Cordova are significantly slower than native applications. especially for graphical-heavy applications.

So key solution is React Native. We can just transform our React Application into React Native but changing some elements. The concepts are same for the both – react and React Native.

  1. When we work on a React component first things we notice – Our component has to a ‘render’ function. And if there is no render function, we got an error.

screen-shot-2016-10-03-at-3-26-45-pm

The best thing is, we never mess with DOM here, but we return a JSX. JSX is  XML-based construct that represents what will be rendered in the DOM.

Lets rndor here: <div className=”main-component”>Hello World</div>

 screen-shot-2016-10-03-at-3-30-12-pm

JSX converts XML coding into functions: 

return React.createElement(“div”, {

           className: “main-component”

 }, “Hello world”);

 So the advantage of this is, We can’t render our components anywhere else than inside of the “render” function, so there is never the concern that we don’t know where exactly our rendered component came from.

  1. In addition to props, components can also have an internal state. The most prominent example of that behavior would be a click counter that updates its value when a button is pressed. The number of clicks itself would be saved in the state. Each of the prop and state change triggers a complete re-render of the component.

 

So now let’s convert our react app into React Native App. Some pre requirements are needed, like we need OS Mac and X Code. Since iOS is currently the only supported platform. System should have Node.JS pre installed. Then Install the React Native Using –

npm install -g react-native-cli

       Then you can Run your ‘FirstNativeApp’ using

 react-native init FirstNativeApp

 It created a FirstNativeApp folder, in which the boilerplate code can be found. Now we have a React app –

screen-shot-2016-10-03-at-3-46-38-pm

Our Aim is to convert this into Native React App. For this we have to follow some simple steps. 

  1. First step is to change requiring the React module to “react-native”.

var React = require(‘react’);  << == >> var React = require(‘react-native’);

 

  • Do you know, there is no DOM in Mobile. So we can not use elements like DIV and SPAN. So we’ll use <View> in place of <DIV> and <Text> in place of <Span>

screen-shot-2016-10-03-at-4-00-23-pm

But here, we can not put text directly in to <DIV>. So We’ll change Hello…. Thing like this :

screen-shot-2016-10-03-at-4-00-09-pm

  • Next thing is React Native doesn’t use CSS. So for this we’ll use inline CSS. Using inline CSS seems bewildering at first. It is similar to the transition React developers had to go through when being confronted with JSX and previously using templating engines.

So here we declare the CSS directly at component level, and so we have all the information we need to see what our component does, the layout it creates, and the styles it applies.

screen-shot-2016-10-03-at-4-02-04-pm

  • Next point is how to handle events in Native React? We want to give an alert message in above example. So here instead of events being directly available on “<View />” components, we need to explicitly use elements that trigger events, in our case a touch event when pressing the view. There are different types of touchable components available, each of them providing a different visual feedback.

screen-shot-2016-10-03-at-4-11-02-pm

  • Now our Native React Application is ready, now time to register – When we do it in react we just write – React.render but in Native React, it is bit different. First we should register our app for the Objective-C side of things which is done using the “AppRegistry” object. Here we can see our FirstNativeApp native app has more lines than react one.

screen-shot-2016-10-03-at-4-19-51-pm

Now you can run your Application. To run the React Native App, we need to replace the contents of the “index.ios.js” file with the piece of code of our transformed app from the last step. Then we just need to open the Xcode project and press the big Run button. First a terminal will open with the React Native server, and then the simulator window will appear.

Press Command +D will show a development menu. Then Click on the Box:

screen-shot-2016-10-03-at-4-26-14-pmscreen-shot-2016-10-03-at-4-26-29-pm

Try this, thing and write me back or comment if you face any issue, We’ll solve it together.

Some Basics React.js beginner should know

React.Js is an emerging programming thing for developers. This is the language which makes hard stuff as easy as easy stuff, but sometime it makes easy stuff as hard as hard stuff, which you do by using simple jQuery or Javasript. Many documentations are available online by using then you can set your environment and can start working with React.JS. but before starting big things you have to know some basics. I learnt some react.JS. sharing my points:

  • First thing you have to be clear, React.JS is not an MVC framework or any other kind of framework. React JS is just a library which renders your views. If you are a MVC guy, you should only have in your mind ‘V’ – Views, nothing else. So always keep this thing in mind otherwise you will end-up with your awesome react code.
  • Second thing, you have to be clear on your all components. Always make them SMALL. This is simple and easy to understand you code to the other developers. So always make your components as small as possible.

Example:

screen-shot-2016-10-02-at-2-47-04-pm

Here I have created a carousal for my Testimonial Section. Simple and small component. <DIV> with only one rendering element – <Slider>.

 

  • Third point is, we should write functional components. There were two types of defining react components :
    • Using ES6 Class:screen-shot-2016-10-02-at-2-36-19-pm
  • Using React.createClass():

screen-shot-2016-10-02-at-2-36-12-pm

But now new update React 0.14 has new ways to define the components:

screen-shot-2016-10-02-at-2-36-26-pm

  • Next most Important thing is we should always use At the time of development when you are a required Prop, It will show an error and which will benefit to you, Catches bugs by preventing silly mistakes. Use of isRequired makes you free from bugs like undefined OR null.

ProTykes look like this :

screen-shot-2016-10-02-at-2-29-29-pm

  • The main and only react specific thing is JSX. JSX is a no-brainer over manually calling createElement. Use of this gives you an disadvantage – it will add some amount of build time complexity.

But this will be solvable usinf Babel.

ES6 features are also important – like constants, arrow functions, default arguments, array and object destructuring, spread and rest operators, string interpolation, iterators and generators, a decent module system, etc.

We round things out with Webpack for bundling our code, and NPM for package management, and we’re now fully JavaScript buzzword compliant 🙂

  • React DEV tools are awesome. We can set up hot module replacement with webpack, so that our page updates as soon as we save our code – no browser refresh required.
  • As in above points I have discussed about ‘V’- views, so the question is where we’ll put our state and logic? So the Answer is here : We all know about Flux ?

Flux is a style for designing web applications. So for the same thing here we’ll use Redux.JS.

You can know more about Flus: https://facebook.github.io/flux/

And Abour Redux.JS: http://redux.js.org/

So I how this will give you a head start on React. Follow the rules/ ricks and tips and create your React application.  🙂