Auto-Generating Z-Indexes with SASS

z-index

Z-index management is one of the most useful things that SASS gives us. We no-longer need to fiddle with numbers, and the order is presented in a direct, visual way. Introducing the mixin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@mixin u-z-index
{
    $z-list:
        '.w-home-banner-arrows'
        '.w-home-banner-pager'
        '.w-home-banner-ad'
        '.w-carousel-previous'
        '.w-carousel-next'
        '.w-bottom-bar-categories-box'
        '.w-bottom-bar-categories-box-sub-category'
        '.w-middle-bar-classifications-box'
        '.w-middle-bar-search-toggle[aria-pressed=true]::after'
        '.w-middle-bar-search-box'
    ;
    $me: "#{&}";
    $z-val: index($z-list, $me);
    z-index: $z-val * 10 + 100;
}

This is how it’s used:

1
2
3
4
5
.w-bottom-bar-categories-box
{
    @include u-z-index;
     
}

Managing Z-indexes is now as simple as adding the mixin to your element, then adding the selector to the list within the mixin. You can change the z-index order by moving the selector lines around in the list. The final z-index will be a result of its index within the list, times 10, plus 100. I start my lists at 110 as there are some javascript libraries that auto-generate z-indexes between 1 and 100. You can remove that part if you don’t need it.

This functionality is achieved by others in different ways, you should check them out too and decide what would work best for your project. Remember, keep it simple unless you can justify the need for added complexity.

Other examples:

https://www.sitepoint.com/better-solution-managing-z-index-sass/

https://www.smashingmagazine.com/2014/06/sassy-z-index-management-for-complex-layouts/

https://jonsuh.com/blog/organizing-z-index-with-sass/

Some of these other examples add z-index ‘categories’ and assign each element to a category. I prefer to do without categories and ensure that each element has a different z-index. These techniques are a great example of how to use new technology to improve the quality of code.

CSS Preprocessors – Write LESS and put some SASS into your styling

sass_0

As a website styler, it can get quite frustrating in this world of CSS, having to endlessly replicate code lines just to target another selector below the one you are styling, it can add up to literally thousands of lines of code, unnecessary code as well which you will eventually have to sift through just to find that line height that seemed like a good idea to set at the time…

Enter the CSS Preprocessor, this little tool will change your styling world forever. Just a precursor though, whilst I will be explaining LESS in this blog post, you can apply the same theory to almost any CSS Preprocessor.

I was forced to use LESS about a year or two ago when looking into using the Bootstrap framework, at first I hated it, it seemed so overly unnecessary, and it didn’t seem to help me at all.

After getting frustrated and just dumping my normal CSS within the LESS files, I realised there must be a reason that such a juggernaut like Bootstrap uses such a tool like this. So I did some homework.

If you are looking for some good tutorials then the best place to start is usually the site where the code comes from. So I made my way to http://lesscss.org and started to read up.

It’s really quite simple, each level you want to select can be nested and styled within itself.

Take this code snippet for example.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
}
body #header {
background: #000;
color: #fff;
}
body #header p {
font-size: 14px;
color: #666;
}
body #header p span {
background: #000;
color: #fff;
}

Quite cumbersome when you have to write out the same classes again and again just to target another selector… If this were done with LESS you can squeeze it into the following.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
#header {
background: #000;
color: #fff;
p {
font-size: 14px;
color: #666;
span {
background: #000;
color: #fff;
}
}
}
}

At first this might seem pointless, you aren’t actually saving any lines of code, but it’s the fact that you don’t have to keep retyping (or copying and pasting) the same selectors again and again.

Also this way you can group your styling and have much cleaner and leaner code.

This is just the tip of the iceberg with LESS though, there is MUCH more that can be done with it. The point of LESS is to use LESS code.

Mixins as they are known in LESS language are snippets of code that you can re-cycle, so you don’t have to keep writing out the same thing time and time again and they also mean you will never have to use that hacky method of search and replace EVER (seriously I mean it).

Take the example below:

.button {
color: #fff;
background: #ff000;
}
.header {
color: #fff;
background: #ff000;
}
.page-title {
color: #fff;
background: #ff000;
}
.brand-highlight {
color: #fff;
background: #ff000;
}

This snippet is one that is used a lot when you are dealing with a business brand colour, for this example the brand colour is red. Now let’s say you wanted to re-use this in an entire new site, but the new brand colour was blue… with CSS you would whip out the old search and replace and hope to god that:

  1. All the spacing was the same…
  2. The exact same hex code was used every single time…
  3. If there were any variations, again, the same hex code was used
  4. There was only 1 style sheet… otherwise you are in for trouble

These are just the things that spring to mind, and I can guarantee that every time you do this, there will be some stupid variation that a designer put in, like a drop shadow that is an alpha with some transparency or a tint colour or SOMETHING like that.

Again this is where LESS will save you literally HOURS of time. The mixin is set once and then is reused throughout the project and can be manipulated without ever having to change the original colour.

See the snippet above, used below with LESS

@brand-primary: #ff000;
.button {
color: #fff;
background: @brand-primary;
}
.header {
color: #fff;
background: @brand-primary;
}
.page-title {
color: #fff;
background: @brand-primary;
}
.brand-highlight {
color: #fff;
background: @brand-primary;
}

To make this even more advanced you can use:

.brand-highlight {
color: #fff;
background: @brand-primary;
text-shadow: darken(@brand-primary, 80%);
}

So now when you change the mixin colour at the start of the code, it will flow through beautifully and change all the styling with one fell swoop (take that Search and replace!)

To touch on the above code as well, LESS also allows you to have the ability to apply mathematical functions to any style so you can have pixel point accuracy, most designers use percentage for opacity or colour changes (like a highlight or hover colour) and this way you can apply it in the same way, so when the client says “just a little lighter” rather than whipping out your hex colour palette, just change the percentage to match and it’s all done for you.

There is A LOT more you can do with these processors, but I thought I would share some easy to explain features which have really changed the way I style.

GOTCHAS

A complex program needs memory

LESS is no exception, you will need your own development server, and you don’t want to be coding in LESS on a live site. It uses resources which converting all the coding to CSS and it is not shy about gobbling them all up. But with that, it will make sure you use proper web development practices, develop on a dev server, save all your changes, and then put them live.

Learning LESS is hard at first

It can be difficult if like me, you can be styling for well over 10 years… I was set in my ways, but over the last 2 years, I have relearnt and been able to take advantage of LESS. It’s not ALWAYS the right time to use LESS If you have a site that you don’t really have access to obtain a dev copy of, or it is quite a simple design, sometimes a CSS prepocessor might not be the right option, so you need to pick and choose your battles. Have fun! Links to some CSS Preprocessors:

  1. Sass – http://sass-lang.com/
  2. Less.js – http://lesscss.org/
  3. Stylus – http://learnboost.github.io/stylus/
  4. CSS-Crush – http://the-echoplex.net/csscrush/
  5. Myth – http://www.myth.io/
  6. Rework – https://github.com/reworkcss/rework

OVER ENGINEERING

over

The days of pure HTML, CSS and Javascript are over. Now we must learn CSS pre-processors and frameworks, multiple Javascript libraries (usually based on jQuery) HTML templating engines based in Javascript, task runners such as grunt and gulp, etc. With all of these tools available, and becoming an ‘industry standard’, it’s easy to misuse them and make a real mess of your website coding.

The reality is, you don’t need any add-on technologies. You can always create websites with highly organised, easily maintainable code, even when using the base technologies.

Modern web development often involves over-engineering. By this, I mean that too much time is spent on setting things up, writing and configuring tools and finding ‘smart’ ways of doing things instead of just doing what needs to be done in a logical manner.

CSS Preprocessors

Nesting

We all know the rule that selectors shouldn’t be nested more than 4 levels deep. However, I disagree with this, as I find that nesting selectors at all will make the code less readable. It’s easy to scan code in a vertical manner, but when my eyes need to also scan horizontally, it makes scanning much less efficient.

If I am looking through a style sheet and I find a class nested a few levels deep, I need to know the parent selectors to understand how the class is being applied. I need to scroll up to see the parent selector, then scroll up again to see its parent selector, then again. It’s not immediately obvious or straight-forward how it will be applied, I need to scan entire blocks of code to understand one line. It’s not a problem if the blocks are small, but there are usually quite a few child selectors under the parent block.

What I often see is a top-level class being used like a namespace. While it may seem neat to organise code this way, it takes more time and effort to understand it. It doesn’t add anything to the code organisation that you couldn’t do with a few line-breaks or comments. The only benefit is reduction of selector repetition. If organising CSS like programming code was that important, we would have adopted JSS instead of CSS.

I prefer to only use nesting for states and, sometimes, pseudo elements.

Media Queries

Another issue I sometimes come across is the use of multiple repeated media queries. Should each selector have its own media query? What about when they’re nested? It can become a bit messy and hard to see the big picture if so much functionality is separated into multiple super small media queries.

I prefer to use a set of media queries per ‘module’ or ‘feature’, so I don’t have a million media queries and yet I also don’t have one big monolithic set of media queries at the end of the file.

Useless complexity

One of the worst examples of investing time into making something that is often unnecessary, useless or even detrimental, would be the idea of wrapping media queries in pre-processor functions or mixins. I can understand the desire to use this when you have a lot of very complex media queries, used often. However, in most cases it’s just not necessary. You will see a line of code like this:

1
@include respond-to($medium) { }

What exactly does this do? It’s media query related, but you will need to go looking for the definition of $medium to know if it is just a pixel value, a query or a key relating to a keymap. Either way, you need to find the query text, the associated pixel values, how to use this function and what options are already available.

You will need to read and understand the definition of the function to see how it implements these variables. Does it use min-width or max-width as a default? Does it have default functionality?

What benefits does this function hold over a set of variables? You don’t need to type the word ‘@media’ anymore, instead you need to write ‘respond-to’. This is replacing a universally understood piece of fundamental CSS with a lesser-known custom implementation.

It’s always interesting to see what you can do with the tools available and how far you can go. However, we are replacing a straight forward set of readable statements with a slightly more cryptic line of code that needs to be investigated and understood by a programmer.

The benefit of this technique relies largely on how complex your media queries are, and how often your media queries are used. For sites that use simple media queries, storing the pixel value in a variable will be just as effective. For slightly more complex queries, you can store the entire query in a variable.

The creator of this technique warns his readers about finding a balance and picking the right tool for the job. I’ve seen this technique used in a way that is detrimental to the project many times.

Before using this technique, you need to consider if it’s the right thing to use for your project. Consider your development environment, project size, tooling and style of coding. Don’t just use this because it’s ‘good / standard practice’. Use it only if it suits your project.

Javascript

Libraries

When you want to read a book, you go to the library and borrow one. However, common practice with Javascript is to borrow the whole library just to read one book. Often, libraries like Bootstrap are included and used just for one feature. One feature that you could write in three lines of code. It’s important to justify the inclusion of an entire library before you do so.

Insane code

A previous company that I used to work for, had outsourced a project to an overseas company. One feature of the website was a little call to action button that would stick to the top right of the screen when the user scrolled past a certain point.

The developers had implemented this by using a collision detection system about a page long. It detected when any part of the element collided with the banner above it, so they knew when to remove the fixed position if the user was scrolling upwards. It was probably ripped from some game engine. I’m surprised they didn’t go one further and program some sort of self-learning AI to achieve the same task.

How many lines of code would it take you to implement that functionality?

Lack of programming knowledge

1
2
3
4
5
6
If (I == true)
 {
     I = false
 } else if (I == false) {
     I = true
 }

Actual code. From a teacher in a web development course. This was back in 2008. It’s memorable, but not in a good way.

This is not as common nowadays as most people know about the ‘not’ operator, but I have seen people implement code to replicate the functionality of the ‘modulus’ operator.

It’s important to know the features of the languages you use.

Conclusion

There are many motivations to complicate your code. To improve maintainability, improve functionality, boredom, being a smartypants, to annoy people for fun etc. However, keep in mind that in a year’s time, you may be the one working with your own code, cursing the developer who made this mess, only to find out that it was you who screwed you over. Yes, I’ve been in that situation, which is how I know. It’s also why I do things simpler and, for the lack of a better term, slightly more old-school than most people when possible.

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.

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.  🙂

Heart of a Layout: CSS Display Properties

Before starting any design, you need work on building blocks of that design, with a strong foundation, you always try new techniques, and creating something awesome that you’re proud of. So for gaining this proud, you should be aware with basics. I know you are an expert and Writing a good CSS is no different for you and it all starts with understanding what you’re working with, before you write a single line of CSS. In a design we have many blocks with different elements, like paragraph with full width, images block with different width and height, and many more. Web browsers that render to a screen defines their own style to govern the default layout of HTML elements. This CSS are called the user agent CSS, and are responsible for a mostly consistent experience across the different Web browsers.

For every HTML element that the WHATWG define some CSS. This CSS is not much different to the CSS we will write, and also can override. WHATWG defines display: block;  for body Tag automatically.

But we can change it in many ways, Like- display: none; OR anything else.

 Let’s understand the display properties: Experiments says <DIV> and <P> behave like same.

 :- Block -:

 p {

display:block;

margin: 0;

}

 

div{

display:block;

}

 

Here both div and p tags are assigned display: block;. Only one thing is different, <p> has some assigned margin. display: block; makes block-level elements, which have the following properties:

  • Bu Default – Occupy full width of a container.
  • Respect top / bottom padding and margin.

Given properties are very useful.

:- Inline -:

display: inline; Very Important style. You can get this property in anchors, spans, strongs, and a slew of other mostly typographical elements by default. Display: Inline; elements allow us to stack HTML tags next to each other, without affecting the layout of pages and these elements ignore most vertical and horizontal layouts. Also ignore the height, top and bottom padding and margin.

inline occupy only the width of their content block – as if they are shrink-wrapping around their content.

:- inline-block -:

display: inline-block; This property gives you the best of inline and block-level elements in one.

Block can be assigned explicit widths They respect vertical margins and padding values.

inline-block will stack with other non-full width elements, until content width reaches the full width of the content block, at which point it will always occupy its own line. Inline elements, in contrast, will always wrap to new lines with adjacent non-full width HTML elements.

 

:- Vertical Alignment -:

Other very helpful attribute of inline-block elements is that they also respect the vertical-align property for differing vertical Ys. inline-block elements respect vertical properties while Block elements don’t respect any vertical-alignment properties and inline elements respect vertical alignment.

 

When To Use What?

Simple way is to start your design by asking some yourself:

Screen Shot 2016-06-05 at 3.16.21 PM

Must Try these display properties carefully.