How to become a Kickass Web Developer in 2021 [Frontend & Backend Tips]

f:id:suniljoshi:20201026212949j:plain

Become Kickass Web Developer

Alright then, so you have decided your path. You want to become a web developer this year.

Welcome to the vast ecosystem of the web! Great choice, but how will you become an awesome dev who loves taking challenges, can implement what needed by the client, or just knows how to debug and solve web-related problems?

The following content which you're about to read will tell you all you need to know to get things done, professionally. Here's how you can become a kickass web dev this year:

What is web development?

Before we jump some nitty-gritty of the languages and frameworks, it is really important to know what exactly your work will be. What you will be doing as a web dev. Without knowledge of the web, you can't become a good developer.

In one sentence, web development is a domain where the work is involved in developing (or building) a website (ora web app) for the internet.

Usually, it is not concerned with the design of a website. It’s all about the coding and programming to enable some functionality on a website.

What a web developer does? When you work as a web developer, you write the code responsible to tell a website how it should function. A web developer can wear multiple hats. For example, a web developer not simply just 'codes' the website, rather they build the website in a certain way so that the end-user or website visitor should have the minimum difficulty while navigating or using the website. Hence you, as a web developer can bring an idea or a design to life by using your coding skills.

Okay then, now you know what this domain is all about, sounds exciting? Here we go with some awesome tips:

General tips for web developers

These are some of the tips all web devs should have whether you're a full-stack or a front-end dev.

1. Always stay updated: The path you've chosen as a web developer is something that changes frequently. As we're progressing with newer technologies, the web, in itself is changing day-by-day. To keep up with these changes, you can:

2. Take inspiration: This is your medicine for your concern, "I don't know what to code!" Taking inspiration from others is not something you should be afraid of, we all need that one idea to convert it into code. Hence, you can visit the following websites:

3. Learn general programming principles: These include code review, collaboration with other developers and maintainers, refactoring and commenting your code, using Clean Code practices, problem-solving and debugging, and of course, testing your code.

4. Document your learning: If you want to progress, then this is the thing you need to do consistently. Whatever you're working on whether it's a project or just learning a new library, document it. This can be in multiple forms like using social media to showcase or simply writing an article. Write what were your achievements or failures while learning a specific topic, create tutorials, etc.

5. Create content: If you're confident enough to know certain topics then don't shy from being creative! You can start your YouTube channel, a newsletter, a course, or even write an e-book. Go further by making some side income while you learn! This is all about helping the developer community.

6. Mentor others: Whether it's your colleague, a junior in college, or even someone who's coming from a different industry, you have an edge of teaching or mentoring them. People are always looking up for mentors while they begin their coding journey, you can be their help!

7. Attend or speak at an event: If you love meeting people and networking then it's highly recommended to attend events, webinars, or conferences worldwide. You can either be a speaker or just be an attendee. This gives you crucial knowledge and lots of information from different minds around the world.

8. Pair program: Here, you and your nerdy friend can work on the same project together. This becomes highly effective when you also need code reviews alongside with ideas for the actual project. You both share knowledge to create a better version of a program.

9. Never give up: When you have such a huge list of information to grasp to write code for the web, it can be overwhelming sometimes. But you should know your goal and never give up. Breaks are important to take. No need to undervalue or undersell yourself.

10. Keep getting feedback: Even if you have tonnes of experience in web development, you will still need to know where you can improve. Whether it's a code-related task or simply about a project idea, you should always get feedback to iterate.

Tips for frontend developers

Front-end web development is the practice of producing HTML, CSS, and JavaScript files for a website so that a user can see and interact with them directly.

1. Have a gist of design: As a front-end dev, you will be working closely with product designers who make the interface or the UI design of a website. Having a bit of knowledge about this doesn't hurt as you will know some of the best practices needed to make a beautiful web interface.

2. Never skip the fundamentals: At the core of a website you make, there are three technologies needed: HTMLCSS, and JavaScript. You need to know about these three before moving further as they are the basic needs. You can start learning about them on Mozilla Developer NetworkW3Schools, or Freecodecamp.

3. Don't underestimate CSS! Most people say CSS isn't much powerful, but there is so much to know about CSS! After going through the basics, you can dive into CSS frameworks like BootstrapTailwind, or Bulma. You can even supercharge your styling workflow by adding pre-processors like SASS and LESS.

4. Pick a framework that suits your needs: No need to hop into the trendiest framework out there. Select one which your project, company, or workflow demands. Start with the official documentation first whether it's ReactVue, or Angular.

Developers, Checkout WrapPixel for some of best & free Angular TemplatesReact Templates and Vue Templates, to help you speed up creating frontend for your project.

WrapPixel's Template

5. Responsive first: More than half of the websites are opened using mobile devices, as a frontend developer you need to code with the responsive first approach so that it doesn't look terrible on multiple devices.

Tips for backend developers

A back-end developer builds and maintains the technology that powers the elements and components which, together, enable the user-facing side of the website to even exist in the first place.

1. Learn a backend language with data structures in mind: Over the backend, you will be dealing with a lot of data. Languages like PHP, Python, or Go can be practiced.

2. Get to know about databases: You need to have at least some of the required knowledge of how databases work, how to work on them etc.

3. Choose the desired framework: You can go for LaravelExpress, or Ruby on Rails.

4. Client-side knowledge: A little bit is harmless as it will be used to integrate your backend logic to the frontend code. You will know how the data is populating into the interface.

5. Learn what sits in the 'middle': It includes topics like middleware, APIs, data security and protection, hosting to the cloud, working on the CI/CD environment, etc.

Now, are you excited to dive into web development? We strongly recommend keeping a tab on these tips to become an all-round web developer. Keep learning and happy coding!

This article is originally posted at WrapPixel - https://www.wrappixel.com/become-kickass-web-developer-2021/

Top 42 React resources every developer should bookmark [Latest]

f:id:suniljoshi:20201022191327j:plain

react resources

Every developer needs resources! Whether you are just starting learning the most popular JavaScript library or you’re already a pro in it, there are an immense number of resources both free and paid from where you can take some inspiration, learn new concepts or just listen to some podcast.

Here, are some of the best ones out there which you as a React dev should bookmark and use it as a reference whenever needed. They range from courses to learn React to some of the coolest events happening worldwide.

Courses

  1. React Tutorial: Learn modern React from scratch, and practice in an intuitive environment. Throughout this course, you will build an online supermarket shopping app with Stripe integration.
  2. React Training: This is a comprehensive list of courses provided by the team of professionals from the React Training group. The same people who made React Router.
  3. React by ui.dev: From React Redux to Router and exclusive events you get all in this course.
  4. Learn React for free: Learn all the key concepts while building two apps and doing interactive coding challenges along the way via the Scrimba’s intuitive platform.
  5. React for Beginners: This is a premium step-by-step training course from Wes Bos to get you building real-world React.js + Firebase apps and website components.
  6. Complete Intro to React, v5: This Frontend Masters course starts from the ground up, getting to using the latest features in React, including hooks, effects, context, and portals.
  7. Building Web Applications with React: A complete collection of individual resources from Pluralsight. It starts by introducing the fundamentals of React. It then dives into how to design, style and server render components, manage state and test and optimize your application.
  8. Kati Frantz’s courses: Kati makes both free and paid React courses which includes technologies like TypeScript, NodeJS and testing.
  9. Epic React: More than a course, Epic React is a series of code-along interactive workshops by Kent C. Dodds which includes topic like Advanced React Patterns, React Performance and more!
  10. React Security: Ryan Chenkie’s React Security is a series of courses all aligned to get you to know how to add essential security features in your React application.

Podcasts

  1. React 30: A 30-minute podcast about React and all things JavaScript.
  2. React Podcast: One of the oldest and most favourite podcasts which covers a variety of topics in the React ecosystem. It has 100+ episodes.
  3. React Roundup: A podcast dedicated to React and the community.

Events

  1. reactjsday: From the organizers of events like JSDay, this year’s ReactJS Day has talks from industry leaders who will talk about testing, React Native, React Hooks and more!
  2. reactiveconf: The yearly conference targeted to connect the European tech community is holding this event with 10 workshops, 5+ speakers, and topics like PWA, Security, Optimizations and much more.
  3. React Wednesdays: React Wednesdays is a weekly chat show with the best and brightest from the React world with TJ VanToll, Principal Developer Advocate.
  4. Byteconf React: Byteconf React is a 100% free two-day conference with the best React speakers and teachers in the world.
  5. Community conferences: An official collection of all the upcoming React events.

Articles/Blogs

  1. ReactJS Official Blog: A definitive thing to bookmark! Get ready to read all the things new to each version of React on their official website.
  2. Scotch.io: An updated list of blog posts and articles are available on the Scotch.io website. Different authors come together under one platform to share their tutorials and courses with others.
  3. Alligator.io: The platform’s goal is to try and make it easy and quick to understand things in various technologies including React.
  4. Smashing Magazine: If you’re looking for high-quality React articles then Smashing Magazine is a must. They have a wide and in-depth tutorial from a variety of topics.
  5. LogRocket Blog: LogRocket’s blogs are updated weekly. They have a bonus section on reference guides as well.
  6. DEV Community: An ever-growing community of developers who write and share their thoughts on the React ecosystem.
  7. Freecodecamp: The beginner’s favourite platform has a bunch of updated and quality articles for React posted regularly.
  8. Robin Wieruch’s Blog: A huge collection of articles comes from Robin who takes on topics like React Hooks, Redux, NodeJS etc.
  9. Dave Ceddia’s Blog: Dave is a software engineer whose articles mainly cover the React ecosystem along with various other technologies like Tailwind, Git, Svelte etc.
  10. Flavio Copes Blog: If you need some bite-sized tutorials or explanations, then Flavio masters it. The articles explain a small problem and solutions.

Books/E-books

  1. React from Zero by Kay Plößer: It’s a 20-lesson book that takes you step-by-step how React works, using simple JavaScript.
  2. React JS Notes for Professionals by Goal Kicker: This book is written by people at Stackoverflow and has over 20 chapters detailing the important parts of ReactJS.
  3. The React Handbook by Flavio Copes: This book focusses heavily on learning some come JavaScript concepts before diving into React topics.
  4. The Road To React by Robin Wieruch: A highly-popular book that comes in three forms – The Bare Essentials, The Essentials and The Professional.
  5. Pure React by Dave Ceddia: This book goes beyond by properly explaining why React is important and teaches you how to build clones of big products like Slack, Reddit, Hacker News and Pinterest.
  6. React Explained by Zac Gordon: Learn all the important React concepts and make a final project at the end databases and CRUD functionality.
  7. Learn React Hooks by Daniel Bugl: In this guide, you’ll be making a complex UI application with React Hooks while also learning about Context API.
  8. Learning React, 2nd Edition by Alex Banks and Eve Porcello: First you will learn how to work with functional programming and the latest ECMAScript features. Then you will be able to look at how React works under the hood.
  9. Fullstack React by Anthony Accomazzo, Nate Murray, Ari Lerner, Clay Allsopp, David Guttman and Tyler McGinnis: This book has a huge resource of 15 chapters, sample apps, detailed explanations and is up-to-date with the recent changes.
  10. React in Action by Mark Tielens Thomas: This book focusses on introducing the front-end developers to the React world, it has ample examples to look onto and also covers React tooling.

React Templates

  1. Reactjs Templates by WrapPixel: They offer high quality and free react admin dashboards and website templates under MIT License. Which can help you to use it in your personal as well as commercial project for free. There also premium react templates included, which has lots of ready to use components with stuning designs. Do check.
  2. React Themes by ThemeForest: Has a variety of react templates. They all are paid templates.
  3. React Templates by Bootstrapdash: Offers some nice free and premium react templates.
  4. React Admin by Coded Themes: They have 1 free and 1 premium react admin template.

We hope these will help you in boosting the React knowledge you need. Keep on exploring the vast ecosystem React provides by keeping a tab on their official website.

This article is originally posted at WrapPixel - https://www.wrappixel.com/best-react-resources/

The Ultimate React Cheat Sheet

f:id:suniljoshi:20201019183141j:plain

react cheat sheet

React is an open-source, front-end, JavaScript library for building user interfaces or UI components. Just like Vuejs, It gives us the ability to create components, layouts etc in our application. In this article we will go through all the fundamentals of Reactjs in this React Cheat Sheet.

Installation

Using React in our application is quite easy as we can add it using the CDN or by using the CLI to install it from npm.

To add React using the CDN, add this script tags in your html

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

Or you can install it using NPM:

npm install react react-dom --save

The --save flag will add react and react-dom into our application depenency.

Using create-react-app

Create React App is a tool that gives you a massive head start when building React apps. It gives us the ability to scaffold a new react project with no configuration. We can install this globally on our local machine by running this command on our terminal:

npm install -g create-react-app

The -g command will install it globally on our local machine.

With this installed, we can now scaffold a react project using this command:

create-react-app <name of project>

When the setup is completed, we can now move into the project and then download the projects dependencies

cd <name of project>
npm install --save

After install, to server your application, run npm start on your terminal.

React DOM

To setup a simple react DOM, we can import ReactDOM, this is what we will use for rendering.

import React from "react";
import ReactDOM from "react-dom";

//define a template
const warning = <h1>Hello,I'm Sunil</h1>;

// ReactDOM.render(root node, mounting point)
ReactDOM.render(warning, document.getElementById("root"));
  • The ReactDOM.render() function takes two arguments, HTML code and an HTML element where the code will be mounted.

Functional Component

This is otherwise known as a stateless component which is is just a plain javascript function which takes props as an argument and returns a react element:

import React from 'react';

const Button = () =>
    <button> Apply</button>

export default Button;

Now to use this component, we can do this:

import React from 'react';

const Button = ({ onClick, className = 'button', children  }) =>
    <button
        onClick={ onClick }
        className={ className }
        type='button'
    >
        { children }
    </button>

export default Button;

Class Component

A Class component acts like a function that receives props, but that function also considers a private internal state as additional input that controls the returned JSX.

import React, { Component } from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div className="main">
                <h1>Helo Devas</h1>
            </div>
        );
    }
}

export default MyComponent;

We can pass in some states:

import React, { Component } from 'react';

class MyComponent () extends Compnent {
    constructor ( props ) {
    super(props);
    this.state = { message: 'Helo Devas' }
    };

    render() {
        return (
            <div className="main">
                <h1>{ this.state.message }</h1>
            </div>
        );
    }
}

export default MyComponent;

Lifecycle Hooks

React component passes through 3 phases which are Mounting, Updating and Unmounting. When a component is about to be mounted, React calls 4 built-in methods:

  • Constructor()
  • getDerivedStateFromProps()
  • render()
  • ComponentDidMount()

Mounting Phases

  • Constructor()

This method is called before anything else in the component, when the component is initiated, and it is the natural place to set up the initial state and other initial values. This method passes a prop as a parameter and always start by calling super(prop) before setting any state or anything else.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • getDerivedStateFromProps()

This method gets called before rendering elements in the DOM. It is invoked after a component is instantiated as well as when it receives new props.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }
static getDerivedStateFromProps(props, state) {
    return {name: props.favcol };
  }

  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • Render()

This method outputs the defined HTML into the DOM. This is a required method.

class Footer extends React.Component {
  render() {
    return (
      <h1>This template will be rendered using the render function</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • ComponentDidMount()

This method gets called immediately after the component is rendered. This is the best place to write statements that requires that the component is already placed in the DOM.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }

  componentDidMount() {
    // Everything here runs after the component has been mounted
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));

Updating Phase

The component updates whenever there is a change in the component state or props. Some react built-in method gets called when the component is in this state.

  • getDerivedStateFromProps:This method gets called immediately a component is updated. This basically does the same thing as the method in the mounting phase.
  • ShouldComponentUpdate: This method returns a boolean(True or False) which specifies whether React should continue with the rendering or not.
shouldComponentUpdate() {
        return true;
    }
  • render:This method gets called when the component is updated. It re-renders the HTML to the DOM with the new values:
    render() {
        return (
          <h1>This is component is changed</h1>
        );
      }
    }
    
    ReactDOM.render(<Footer />, document.getElementById('root'));
  • getSnapshotBeforeUpdate: This method gives you the ability to have access to the props and state before the component is updated.
    getSnapshotBeforeUpdate(prevProps, prevState) {
        // get acces to the prepious state here
      }
  • ComponentDidUpdate: This method gets called after the component has been updated.
    componentDidUpdate() {
        // do something gere.
       // log the presents state of the component
      }

Unmounting Phase

This is a state where react removes a component from the DOM. This phase comes with a componentWillUnmount built-in method. The method gets called when the component is about to be removed:

componentWillUnmount() {
    alert("Component has been removed");
  }

Props

Props is a concept used in passing data from one component to another. basically it is used for data communication:

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="app">
                <p>My App {this.props.name}</p>
            </div>
        );
    }
}

//passing the data into the component
class Index extends Component {
    render() {
        return (
            <div className="app">
                <App name="Sunil"/>
            </div>
        );
    }
}

export default Index;

React Map

We can iterate through items using the map method. Just like you could use it in Vanilla js, we can have an array of items and then use the map method:

let test = [1,2,3,4,5,6];
const numberList = test.map(number=>console.log(number))

We can also use it in our react component like this:

function App() {
  const people = ['Wisdom', 'Ekpot', 'Sunil','Nirav'];

  return (
    <ul>
      {people.map(person => <Person key={person} name={person} />)}
    </ul>
  );
}

Here we are passing it as an array to the component.

Events

Just like any other framework or library, we have the ability to bind event listeners to our template, this events listen to methods defined. In React, we could define a click event like this:

function App() {

function logSomething() {
    console.log(`Hello i'm sunil`)
  }

return (
    <div>
      <button onClick={logSomething}>Submit</button>
    </div>
  );
}

We can also use the change event listeners too on input fields:

function App() {

function detectChange() {
    console.log(`Changing`)
  }

return (
    <div>
      <input type="text" name="myInput" onChange={detectChange} />
    </div>
  );
}

State

State is basically storing of data. We can store objects, arrays, strings and then use them in our react components. To use the data stored in the state, we can use the this keyword

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {messages: 0};
    } 

    render() {
        return (
            <div className="app">
                <p>My messages: {this.state.messages}</p>
            </div>
        );
    }
}

export default App;

React HMR

The hot module reload retains the application state which is lost during a full reload. It saves compilation time as it only updates what was changed and not the entire application:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';

ReactDOM.render( <MyComponent />, document.getElementById('root') );

if (module.hot) {
    module.hot.accept();
}

React Router

To handling routing in react, we have to install the react router using NPM:

npm i --save react-router-dom

To route to a component, we can use the <Route /> tag which takes the path and the component we routing to as an attribute:

import { 
  BrowserRouter, 
  Route 
} from 'react-router-dom'

const Hello = () => <h1>Hello world!</h1>

const App = () => (
  <BrowserRouter>
    <div>
      <Route path="/hello" component={Hello} />
    </div>
  </BrowserRouter>
)

React State Hooks

This is basically a state management system. To use this, we have to import useState from react. lets write a simple method which will increment the value of a state when a button is clicked:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

React Templates

Well as above mentioned thins of react cheat sheet will help you creating your project quicker, there is other option also available, which can save your time. Reactjs Templates are always best to learn as well as to use in your react project to make it complete faster. It gives you many ready to use and well designed components, which will increase your speed of creating project. Do checkout WrapPixel for best react templates.

This article is originally posted at WrapPixel - https://www.wrappixel.com/react-cheat-sheet/

Angular Cheat Sheet

f:id:suniljoshi:20201015200205j:plain

Angular Cheat Sheet

Angular is a TypeScript based open-source web application framework used in building both web and mobile based applications. In this article, we will go through some of the angular features by explaining some of its core API. You can follow this angular cheat sheet and use in your project.

Angular CLI

Angular gives us the ability to do a whole lot using their CLI. You can config the entire application by just using the CLI. Here are some of the commands:

  • npm install -g @angular/cli : This command will install the Angular CLI into our local machine using npm.
  • ng new <application name> : This will setup a new Angular application using the ng new command.
  • ng new <application name> --prefix best : This create a new project and set the projects prefix to new.
  • ng new --help: This returns all available Angular command list.
  • ng lint my-app: This command checks our entire application for any linting warnings.
  • ng lint my-app --fix: If there are any form of linting errors, this command will fix it.
  • ng lint my-app --format stylish : This formats our entire codebase.
  • ng lint my-app --help: This command returns all the available linting command list.
  • ng add <package name>: This command will use your package manager to download new dependencies and update the project with configuration changes.
  • ng generate component <name>: This will create a new component on our application. We can also use the ng g c <name> shorthand to do this.
  • ng g d <directive name>: This command angular directive.
  • ng g s <service name> : Creates a new Javascript class based service.
  • ng g p <pipe name>: Generates a new pipe
  • ng g cl <destination> : This will create a new class in the specified directory.
  • ng build: Builds the application for production and stores it in the dist directory.
  • ng serve -o: Serves the application by opening up the application in a browser using any port 4200 or any available port.
  • ng serve -ssl: serves the application using ssl

Angular Lifecycle Hooks

A component in Angular has a life-cycle, a number of different phases it goes through from birth to death.We can hook into those different phases to get some pretty fine grained control of our application.Here are some of the hooks:

  • ngOnChanges: This is called whenever one of input properties change.
  • ngOnInit: This is called immediately after ngOnChanges is completed and it is called once.
  • ngOnDestroy: Called before angular destroys a directory or component
  • ngDoCheck: Whenever a change detection is ran, this is called.
  • ngAfterContentInit: Invoked after Angular performs any content projection into the component’s view.
  • ngAfterContentChecked:This is called each time the content of the given component has been checked by the change detection mechanism of Angular.
  • ngAfterViewInit This is called when the component’s view has been fully initialized.
  • ngAfterViewChecked: Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.

How Angular Hooks are used

Always remember that hooks working in a component or directory, so use them in our component, we can do this:

`class ComponentName {
    @Input('data') data: Data;
    constructor() {
        console.log(`new - data is ${this.data}`);
    }
    ngOnChanges() {
        console.log(`ngOnChanges - data is ${this.data}`);
    }
    ngOnInit() {
        console.log(`ngOnInit  - data is ${this.data}`);
    }
    ngDoCheck() {
        console.log("ngDoCheck")
    }
    ngAfterContentInit() {
        console.log("ngAfterContentInit");
    }
    ngAfterContentChecked() {
        console.log("ngAfterContentChecked");
    }
    ngAfterViewInit() {
        console.log("ngAfterViewInit");
    }
    ngAfterViewChecked() {
        console.log("ngAfterViewChecked");
    }
    ngOnDestroy() {
        console.log("ngOnDestroy");
    }
}

Component DOM

Angular comes with its DOM features where you can do a whole lot from binding of data and defining of dynamic styles. Let’s take a look at some features: Before we dive into the features, a simple component.ts file is in this manner:

import { Component } from '@angular/core';
@Component({
    // component attributes
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.less']
})
export class AppComponent {
    name: 'Sunil';
}

Lets look at some template syntax:

  • Interpolation: using {{data to be displayed}} will display dynamic content from the ts file.
  • <button (click)="callMethod()" ... /> : Adding Click events to buttons to call a method defined in the ts file
  • <button *ngIf="loading" ... />: Adding Conditionals to to elements. Conditionals have to listen to truthy or falsy value.
  • *ngFor="let item of items``": iterate throught a defined list of items.Picture this as a for loop.
  • <div [ngClass]="{green: isTrue(), bold: itTrue()}"/>: Adding dynamic classes based on conditionals.
  • <div [ngStyle]="{'color': isTrue() ? '#bbb' : '#ccc'}"/>: Adding dynamic styles to template based on conditions

Component Communication

Passing data from one component to another can be a little bit tricky in Angular. You can pass data from child to parent, parent to parent and between two unrelated components:

  • input(): This method helps To pass value into child component.
export class SampleComponent {
        @Input() value: 'Some Data should go in here';
        }

Child components are registered in parents component like this:

<child-component [value]="data"></child-component>
  • output(): This method Emits event to the parent component. Bunch of data can be passed into emitted event which makes it a medium of passing data from child to parent:

To Emit the event from the child component:

@Output() myEvent: EventEmitter < MyModel > = new EventEmitter();
calledEvt(item: MyModel) {
    this.myEvent.emit(item);
}

And then the parent component listens to that event:

<parent-component 
(myEvent)="callMethod()"></parent-component>

Angular Routing

Routing is another cool feature of Angular, with the Angular Routing system we can navigate through pages and even add route guards.

  • Component Routing: We can define routes in our application by defining the path and the component to be rendered:
    const routes: Routes = [
      { path: 'home', component:HomeComponent },
      { path: 'blog/:id', component: BlogPostCompoent },
        { path: '**', component: PageNotFoundComponent }
    ];

For routing to work, add this the your angular.module.ts file:

RouterModule.forRoot(routes)

There are situations where by you want to keep track of what is happening in your routes, you can add this to enable tracking in your angular project:

RouterModule.forRoot(routes,{enableTracking:true})

To navigate through pages in Angular, we can use the routerLink attribute which takes in the name of the component we are routing to:

<a routerLink="/home" routerLinkActive="active"> Crisis Center</a>

The routerLinkActive="active``" will add an active class to the link when active.

Writing Route Guards

We can define guard for route authentication. We can use the CanActivate class to do this:

class AlwaysAuthGuard implements CanActivate {        
        canActivate() {
                return true;
        }
}

To use this rote guard in our routes we can define it here:

const routes: Routes = [
  { path: 'home', component:HomeComponent },
  { path: 'blog/:id', component: BlogPostCompoent,canActivate: [AlwaysAuthGuard],  },
    { path: '**', component: PageNotFoundComponent }
];

Angular Services

Angular services comes in handy when you can to do things like handling of http request and seeding of data on your application.They focus on presenting data and delegate data access to a service.

@Injectable()
export class MyService {
    public users: Users[];
    constructor() { }
    getAllUsers() {
        // some implementation
    }
}

To use this service in your component, import it using the import statement and then register it in the constructor

import MyService from '<path>'
constructor(private UserService: MyService) 

To make things easier, we can use this command to generate a service in Angular

ng g s <service name>

Http Service

Angular comes with its own http service for making http request. To use it, you have to first of all import it into your root module:

import { HttpClientModule} from "@angular/common/http";

After importing it, we can now use it inside our service for making of http request:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
    providedIn: 'root'
})
export class UserService {
    constructor(private http: HttpClient) { }
    getAllUsers() {
        return this.http.get(`${baseURL}admin/list-users`);
    }
}

Http Interceptors

An interceptor is a piece of code that gets activated for every single HTTP request received by your application. Picture an interceptor as a middleware in nodejs where by where http request made is passed through this piece of code.

To define an interceptor create a http-interceptor.ts file inside your src directory and add this:

import { Injectable } from '@angular/core';
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse,
    HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
    providedIn: 'root'
})
export class HttpConfigInterceptor implements HttpInterceptor {
    constructor() { }
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        // Get the auth token from  localstorage.
        const authToken = localStorage.getItem('token');
        // Clone the request and replace the original headers with
        // cloned headers, updated with the authorization.
        const authReq = req.clone({
            headers: req.headers.set('Authorization', authToken)
        });
        // send cloned request with header to the next handler.
        return next.handle(authReq);
    }
}

This is a simple interceptor which checks if users has token in their device localstorage. If the user does , it will pass the token in all the http headers.

Pipes

Pipes in Angular gives us the ability to transform data to any specific format. For example you can write a simple pipe that will format an integer to a currency format or format dates to any form. Angular comes with some built in pipes like the date and currency pipe.

We can define our own custom pipes too by doing this:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'exponentialStrength' })
export class ExponentialStrengthPipe implements PipeTransform {
    transform(value: number, exponent?: number): number {
        return Math.pow(value, isNaN(exponent) ? 1 : exponent);
    }
}

to use a pipe in our component we can do this:

    {{power | exponentialStrength: factor}}

Free Angular Templates by WrapPixel

Well, i hope you have enjoyed our Angular Cheat Sheet and it will help while developing in Angular. Same way, Angular templates also can help you with your project. As they come with stunningly designed interfaces and ready to use components, which can save your time and money. Also you will be able to find best free angular templates by WraPixel. You can download that with zero investment and use it in your personal as well as commercial projects.

This post is originally posted at WrapPixel. https://www.wrappixel.com/angular-cheat-sheet/

What the heck is Vue Vite?

f:id:suniljoshi:20201009152347j:plain

Vue Vite

Vite is a Lightning fast cold server that offers instant hot modules replacement and True on-demand compilation. This tool was created by the Creator of Vuejs, but this doesn’t mean that it can only be used in Vuejs, it could be used by libraries like Reactjs.

Vite allows you to serve your code via native ES Module imports during development, allowing you to develop Vue single file components without a bundle step.

Getting Started with Vite

Let’s take a look at how we can use Vite. Primarily Vite was built for Vue 3 but nevertheless we can still use it in our Vue 2 Application.

Head over to any directory of your choice and open up your terminal and type the following:

npx create-vite-app <name-of-project>

After running this command, you will have to move into your project directory by using the cd command and the install run npm install to install application dependency.

cd vite-test
npm install
code.

The code, the command will open up our application in Vs code.

Next up we can run npm run dev to run our application.

By default, Vite runs on port 3000, so we can access our application using localhost:3000

Now that our application is running, let’s see how Hot Module Replacement actually works.

We will be using the HelloWorld.vue component inside the components folder to test how the Hot Module Replacement work. The codes there actually looks like this:

<template>
  <h5>{{ msg }}</h5>
  <button @click="count++">count is: {{ count }}</button>
  <p>
    Edit
    <code>components/HelloWorld.vue</code> to test hot module replacement.
  </p>
</template>
<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      count: 0,
    };
  },
};
</script>

If you actually change anything in the markup, you will notice that’s the reload time is much faster than the normal Vuejs Application.

If you take a look at the main.js file you will see that it’s still running on Vuejs under the hood.

If we inspect our code on the browser, we will see that it is calling the main.js file as a module

Follow up on the main.js file you will see that Vite serves modules instead of a bundle which actually makes the application quite faster.

Note that all your Vuejs codes will still run effectively.

Installing Vue Router in Vite

You could still install your normal vuejs packages into your vite application like the Vue router by running:

npm i --save vue-router@v4.0.0-alpha.11

This will install the latest version of the Vue Router into your application. Next up create a router.js file and define some routes:

import {
    createWebHistory,
    createRouter
} from "vue-router";
import Home from "./components/HelloWorld.vue";
const history = createWebHistory();
const routes = [{
        path: "/",
        component: Home
    },
];
const router = createRouter({
    history,
    routes
});
export default router;

After doing this we can now register our router.js file in our main.js file like this:

import {
    createApp
} from 'vue'
import App from './App.vue'
import './index.css'
import router from "./router";


createApp(App).use(router).mount('#app')

With this done, we have to change our App.vue root component to this so that it will render all our components:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3.0 + Vite" />
  <router-view />
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
  name: "App",
  components: {
    HelloWorld,
  },
};
</script>

And there you go you can register any other custom route of your choice.

Looking for Vue Templates?

  • Try our Vuejs Templates and create stunning web applications for unlimited client projects and personal projects.
  • Start building web applications and products using our Free Vuejs Templates without any investment.

Conclusion

The Vuejs Vite is still Experimental and will be fully functional in Vue 3. You could still integrate it into your Vue 2 applications just to get more familiarity on how it works.

This article is originally posted at WrapPixel - https://www.wrappixel.com/what-the-heck-is-vite/

What is React? Why is it leading in Website Development?

f:id:suniljoshi:20201007173222p:plain

What is React?

We have been witnessing the epic growth in technology within a decade. But what excites us mesmerising ability and infrastructure that has been build up. And we have also experienced the amazing features of react templates that is widely used for different projects. If you press a rewind button and look back things looked so clumsy and unstructured that we were not able to focus on productivity. We were also not able to focus on innovation, conceptual ideas, growth hacks, and an optimized approach over the traditional a

pproach. But today, things have drastically changed and we are enjoying the advantages to the maximum.

In the current situation, frameworks have been playing an instrumental role in diversifying developer experience. We have technologies, libraries, plugins, add-ons, elements, and other resources that have simplified web development with a minimalistic approach. Above all, front-end web development is significantly bringing the transformation with design, development, and conceptual ideas. This helps to create react template for websites. And all businesses always look for an optimistic approach technology stack that can enhance their work culture and reduce overall development cost as well as time. Currently, you have a wide range of frameworks that are agile and focuses on a modular design. But React.js has been gaining popularity ever since developers came to know about its significant features.

The inside story of React.js Library

So, the first question that strikes your mind is about the React.js library.

What is it? Why developers love it so much?

It will be too early to get into React.js discussion but let us first understand by the term “JavaScript”. In common language, it is a scripting language to hold dynamic web content for a website. Generally, dynamic web content means text, videos, audios, animations, images, forms, and whatnot. You can also create react js themes for website that add styling and effects for better user experience. So, in short, while visiting a website whatever events that are happening around while click on a button is almost JavaScript behind it. Fine, let’s get back to React.js discussion.

React.js is an open-source JavaScript library powered by Facebook. One of its secret sauce for getting such popularity is its huge strong community of developers. And you know very well when there are lots of like-minded behind one cause how amazing and thrilling it becomes. Usually, the React.js library is used for developing a user interface on a website. This is highly favourable for developing eCommerce websites. You can also create react admin dashboard template exclusively for eCommerce website that will enhance the design and responsiveness. Interestingly, this library was developed to build up large scale applications for different industries.

Today, React.js has evolved to be one of the most prominent library ever to be used and it’s still evolving at its best. Nobody knew back in the year 2012 that this library could be loved by thousands of developers when this was developed just for Facebook. Now, just think for a while such a small project that moment and today platforms like Airbnb, Instagram have been built upon this. Wow!!! It’s an amazing thing because you have lots of features to play with and develop an application for your venture or commercial projects.

The secret sauce of React.js Library

Today, if you ask any developer about React.js library, what they think? The answer would be super cool.

Why so?

The reason behind its popularity is its capability and versatility. As we discussed earlier, this library is extensively used for developing user interfaces i.e. UIs.

Do you know what that means?

It gives you extra space to create your interface with the help of elements like navigation menus, headers, footers, buttons, search bars, and other essentials. Being a developer you cannot always manually take control of a website. Especially, when you have multiple projects to handle simultaneously without any delay. There are widely free react website templates available that can be used all at once.

Another important aspect is the reusable library codes at various places within your projects. This largely saves time, helps to cut down cost, and of course energy utilized per project.

There are a few reasons why developers and businesses prefer using React.js:-

  • They are highly flexible to use across the websites.
  • You can breakdown the code into libraries and clean up the coding environment for more visibility and productivity.
  • It provides toolset which is open source and easy to use like Redux and Flux.
  • JSX (JavaScript Extension) which is a React extension creates a DOM that enables developers to easily arrange webpages and add dynamic web content.
  • Virtual DOM is something crated by React.js that identifies what are the areas within a Dom requires any further modification while an event is executed.

Moreover, React.js helps to react dashboard used widely for a different set of projects by developers around the world. You can even create web UI kits to get you going with hands-on elements and avoid creating again.

Conclusion

We looked upon how React.js library is changing the definition of web development processes with so much ease and convenience like never before. It offers a wide range of resources that you can easily implement and save hundreds of valuable hours. Isn’t it great? Well, you also explored the secret sauce behind React.js library and real reasons why developers love this. I hope you have enjoyed this blog and your love for React.js may have evolved even more intense.

Till then happy coding!!!

This blog is originally posted at WrapPixel - 

https://www.wrappixel.com/what-is-react/

Vue Lifecycle Hooks

f:id:suniljoshi:20201005140820j:plain

Vue Lifecycle Hooks

In this tutorial you will learn and gain understanding of Vue.js lifecycle Hooks. you will also gain in-depth understanding of how components are created and destroyed behind the scenes. 

Lifecycle hooks are the entry point to virtually all front-end frameworks out there, having a good understanding of when your components are created, mounted, updated and destroyed is essential to understanding the library reactivity. 

Understanding Lifecycle Hooks in Vue.js is fairly easy. The diagram below is an illustration of a full lifecycle of a Vue.js component.

Vuejs Lifecycle Hooks

Watch how the lifecycle hooks are changing at different stages of the vue template compilation.

According to Vue.js documentation each Vue instance goes through a series of initialization steps when it’s created. – for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.

Vue Created Hooks

BeforeCreate Hook

The beforeCreated hook is the first hook on the initialisation stage, it is triggered before the instance is created, hence the reactivity is not set up on at this state. This means that we you can’t access or update data. If had data coming from your back-end API, calling it within the beforeCreated hook will return undefined. See Example.

<script>
  export default {
    beforeCreated(){
      console.log(data);
      //This will return undefined 
    }
  }
</script>

Created Hook

The created hook is triggered when the component is created, here we have access to the component’s data and reactivity is created. However, templates and virtual DOM are not yet mounted within this hook. See Example below:

<script>
  export default {
    data(){
      return{
        message: "I am learning Vue lifecycle hooks"
      }
    },

    computed:{
      messageChange(){
        console.log(`This will look up to ${this.message} for changes`);
        return this.messages 
      }
    },
    
    created(){
      this.message = "now the message is changed";
      console.log(`messageChange will be updated since reactivity is present`);
    }
  }
</script>

Vue Mounted Hooks

BeforeMount Hook

The beforeMount hook is triggered before the initial render of the Virtual DOM and compilation of template or render functions. Use of this hook during server-side rendering is not recommended it can’t be called after render. See Example:

<script>
  export default {
    beforeMount(){
      console.log(`${this.el} is about to be mount`);
    }
</script>

Mounted Hook

The mounted hook full reactivity is established, templates, and rendered DOM (via. this.$el).

The mounted hook is reported to be the most used lifecycle hook. Most people use it for fetching data for their component (I recommend using Created Hook). See example:

<template>
  <p>Text inside a component</p>
</template>

<script>
  export default {
    mounted(){
      console.log(this.$el.textContent);
      //This will return the text from the template 
    }
</script>

Vue Updating Hooks

Updating hooks are triggered whenever a reactive property used by your component changes, or through user input causes it to re-render. They updating hooks allow you to hook into the watch-compute-render cycle for your component. 

You can use it if you want to know when you component re-renders. To target the state of a reactive component please computed property or watchers instead.

BeforeUpdate Hook

The beforeUpdate Hook is triggered before a component is re-rendered, it is initiated when data changes in a component. This is a good place to track the state of a reactive component before it is rendered. See Example:

<script>
  export default {
    data(){
      n: 1,
    },
    
    beforeUpdate(){
      console.log(this.n) //sets the value of n to 300 after 1,500 seconds;
    },
    
    created(){
      setTimeOut(() => {
        this.n = 300
      }, 1500);
    }
</script>

Updated Hook

The updated hook is called after a data change causes the virtual DOM to be re-rendered and patched. The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead.

<template>
  <p ref="dom-element">{{name}}</p>
</template>

<script>
export default {
  data() {
    return {
      name: "Emmanuel Etukudo"
    }
  },

  updated() {
    // Track update on the DOM element.
    console.log(this.$refs['dom-element'].textContent === this.name)
  },

  created() {
    setTimeout(() => {
      this.name = "John Doe"
    }, 1000)
  }
}
</script>

Destruction Hooks

Destruction hooks are used to perform actions when your components are destroyed, such as remove component-based events. They when components are removed from the DOM.

BeforeDestroy Hook

The beforeDestroy hook is triggered before a Vue instance is destroyed. At this stage the instance is still fully functional. 

<script>
export default {
  data() {
    return {
      accessToken: localStorage.getItem('accessToken'),
    }
  },


  beforeDestroy() {
    // Remove the token.
    localStorage.removeItem('accessToken');
  },  
}
</script>

Destroyed Hook

The destroyedHook is triggered after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed. 

<script>
export default {
  destroyed() {
    console.log(this) // Nothing is left to log
  }
}
</script>

There are two other hooks that are not captured in this article there are keep-alive hooks the Activate & Deactivated. You can look them up on Vue documentation website. Thank you for reading, drop your comments I will like to read from you.

This article is originally published at WrapPixel - 

Vuejs Lifecycle Hooks | Vue Lifecycle | Vuejs Component Lifecycle