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.

Create a Child Theme For Your Theme Customisations – WordPress

Hello! If you’re new to WordPress, the thought of tinkering with its code can be a daunting one. But in reality, there are many simple things you can do in order to customise the look and feel of your site without risking disaster.

I recommended that you avoid making changes to themes directly. Creating child themes and working with offline files are the safest ways to make any changes to the code. Working this way means that way if you do happen to inadvertently create any issues on your site while tweaking it, you have the original files and can quickly re-upload them to overwrite your changes.

With that said, let’s take a look at what you can do to make get started customising your WordPress design.

Create a Child Theme For Your Theme Customizations

The recommended option for doing any form of theme customization in WordPress is to use a child theme. A child theme is a theme that inherits the style and functionality of another theme, called a parent theme.

Child themes allow you to add new functionality and style changes without ever altering the parent theme files. This is especially useful if you ever update the parent theme. If you have made changes directly to the parent theme, any update will wipe them out and you will need to spend time recreating them all.

Child themes are never touched when a parent theme is updated, making them the perfect way to alter your design.

Creating a child theme is a simple process. All you need to do is create one folder and one file. On your local computer, create a folder with the name of your child theme. The most sensible way to name it is simply parentthemename-child. So if you were creating a child theme for our Canvas theme framework, you would call it canvas-child. You might also add a unique identifier onto this name, like canvas-child-yourname.

Create a file called style.css within the new folder (you can do this with a text editor — just remember to add the .css suffix. This file needs specific information inserted into it so that it knows it is a child theme. Add the following code within your style.css file:

/*
Theme Name: My Child Theme
Theme URI: http://mysite.com/
Description: This is a custom child theme I have created.
Author: My Name
Author URI: http://mysite.com/
Template: parenttheme
Version: 0.1
*/

This code contains mostly generic information, but there is one line you must change in order for the child theme to work. The Template line must be changed to show the name of the parent theme you are relating your child theme to (e.g. “Canvas”).

With this information added there is one other important step required. As it stands your child theme has no styling information whatsoever. In order to give it the same initial design as your parent theme you need to add the following line of code:

@import url("../parenttheme/style.css");

In this code you will need to alter the parent line to match the folder name of your parent theme.

Once you have made these changes and saved your style.css file it is time to add the child theme to your WordPress installation. You can do this by connecting to your web host with an FTP program (such as Filezilla) and browsing to the /wp-content/themes/ folder. Once you are there you should upload the child theme folder containing your new style.css file.

With the folder uploaded you should then be able to see and activate the child theme in your Themes area of your WordPress dashboard. You can now edit the style.css theme of your child theme to make design tweaks while retaining the basic theme design from the parent theme.

For more complicated customizations to your child theme you can include a functions.php file. This file allows you to change the functionality of your theme and should be created and added to the child theme folder when you want to make changes to your theme’s functionality.

WordPress have created a detailed section in their codex discussing child themes if you would like to learn more about them.

Edit the Style.css File to Make Customizations

There are a vast number of options you can add to your stylesheet to change your design. These changes are common to all themes, though most themes include custom section names that will vary slightly depending on the parent theme you are using.

Adding code to your style.css file can enable you to:

  • Change the color scheme of your website
  • Alter the typography and text size
  • Move sections of the site around (such as the navigation bar)
  • Change the way images are displayed
  • Add or remove design information depending on the area of the site
  • Make thousands of other design tweaks

Let’s take a quick look at a one of the simple styling options available to you.

Changing the Link Style

Whenever you add a link to your site they are all usually controlled by a simple style option. There are four link states that will need to be looked at. They are:

  • a:link (or just “a”) – this is a normal, unvisited link
  • a:hover – this is what happens when you hover over a link
  • a:visited – this is a link the user has already visited
  • a:active – this is a link at the moment it is clicked

You can use all of these options if you like, but the important ones are the unvisited link and the hover link. For our example, let’s make all of our links red with no other style decoration and the links you hover over have an underline style decoration:

a {
  color:#ff0000;
  text-decoration:none;
}
 
a:hover {
  color:#ff0000;
  text-decoration:underline;
}

If you are using the Canvas theme we covered a small selection of tweaks that you can make to the styles.css and functions.php files.

Use Custom Code Rather Than Plugins

Code
Plugins are a wonderful aspect of the WordPress community. There are plugins out there that allow you to transform your website and enable you to do practically anything you can think of. However, constantly adding plugins is a great way to make your website bloated and slow its load times down to a crawl.

Plugins often require more code than is necessary for the jobs they carry out, simply because of the manner in which they interact with the core WordPress software. Each plugin also comes with management issues as you need to spend time updating them, as well as potential security issues if the plugin hasn’t been updated by the developer in a long time.

There are plugins out there that resolve one simple design aspect of your site, but often require additional code and files. Many of them can be replicated with a few lines of code added to the correct files which will reduce the overall load on your website and keep things tidier.

Let’s take a simple example. There are plugins out there that allow you to remove the titles from your WordPress pages on a page-by-page basis. That can be a useful feature if you want to hide the title of certain pages in order to give readers a smooth transition into the content.

However, with a few simple lines of code you can achieve the same effect. To show you how simple this can be, here is the code to add to your style.css file to do this with the Canvas theme:

.page-id-xxxx .title {
display: none;
}

In that example, replacing the xxxx with the page ID number will remove the title from that specific page. Simply add the code for every page you want to remove the title from.

Plugins for more complex jobs are essential and part of what makes WordPress great, but before you add one for any simple tasks on your site, take the time to stop and do a little research. You will often find a simple piece of code that can do the job instead.

I’ve talked about the danger of plugin ignorance before, but it really should be repeated. Adding plugins to your site without investigating whether there is a simple way to replicate its function is ignorant at best and lazy at worst. Every time you install a plugin you are putting the health and speed of your website into someone else’s hands.

Start Customizing Your Own Site Design

There are a vast number of changes you can make to customize WordPress to suit your own needs. They range from simple tweaks, to customizing color schemes, to the extremely complicated changes that alter the structure of your website.

WordPress customization can seem like a scary process to begin with, especially if you are new to the CMS. There are themes (like Canvas) that allow you to make some of those customizations with a point-and-click style design menu that help to take away some of that initial fear. These are amazing for you in the beginning of your customization journey.

However, if you spend some time using a child theme and the style.css file, you will learn to play with the building blocks of WordPress to create stunning website designs.

Have you started your own journey into WordPress customization and have any advice to share? Please let us know in the comments below.

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