Latest Web, Mobile technology, News & More Blogs

Our Blogs

Dive into the latest insights from the IT industry, updates on disruptive technologies, and business aiding products.

Getting started with React and TypeScript

What is TypeScript?

TypeScript is a typed superset of JavaScript, that makes the React components more resilient without complex building and coding. It works on all browsers and OS and assists in reducing compile-time errors. All the features of JavaScript are available in TypeScript as TypeScript is a superset of it. Some of the most important features of TyoeScript which aid in efficient development include code refactoring, type checking, navigation features and so on.

Features that TypeScript adds to ReactJs

There are many advanced features added to ReactJs, that enable easy and efficient development in React. Some of the important features added by TypeScript are,

  • Strongly types tuples and arrays
  • Reusable types with generics
  • Type annotations and inference
  • The never and unknown type
  • Union and Intersection types

Why use TypeScript with React?

You may even ask, “why should I use TypeScript in React when JS is available? What are all the benefits I can get?”. Let’s go for the answers to this question now.

  • Imagine typing a long paragraph for your friend on your mobile. If your keyboard keeps on giving you suggestions, will you complete typing much faster right? That’s the same here. TypeScript will provide you options and suggestions while developing code for your application in React, which makes your development process much easier and faster.
  • Imagine the same situation, but now besides providing suggestions, it also highlights your errors and insists that you correct them. You will type much faster and you need not read the whole passage for correcting errors right?  Like that, TypeScript highlights your errors and typos before running them, which enables us to save time we spend on fixing bugs and maintain consistent code. This error-correction feature makes TypeScript the most favorite of all the React developers.
  • Using TypeScript, we can add types to functions, properties, and variables that make the code understandable to us. By using this we can read and understand the code much easier.
  • TypeScript enables refactoring of the code and makes the updation without making any changes to its behaviors. It also improves the features of JS and it is compatible with any browser.

Read our article on – Why is React Native the best for Mobile App Development?

How to get started using TypeScript?

You can start using TypeScript by using the Create React App developed by Facebook by importing the create-react-app npm package. The CRA will provide many built-in features, Webpack, hot reloading development that assist you during the entire development process.

To ensure type-checked tests don’t make a mismatch between the development editor and CRA’s output, another npm script known as “test:tsc”: “tsc -p tsconfig.test.json -w” should be used. After the completion of type-checking tests, you can now successfully start creating your app using React using TypeScript.

  • To use CRA, npx create-react-app my-app –template typescript command should be run.  For this, you need the latest version 5.2 of Node.js and npm, a code editor, and CRA.
  • After that, some extensions such as .tsx, tsconfig.json, react-app-env.d.ts should be used. Here tsx stands for TypeScript JSX.
  • After this, run it in development mode by running the start npm script.
  • To set up ESLint and Prettier, install the dependencies
    • yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react –dev
  • At root, create the .eslintrc.js file
  • Add Prettier dev dependencies
    • yarn add prettier eslint-config-prettier eslint-plugin-prettier –dev
  • At root, create .prettierrc.js file
  • Update the files.
  • Followed by that, update the .vscode/settings.json (allows you to fix your code before running)
  • While creating interfaces, follow the react-typescript-cheatsheet guidelines.
  • While developing an application in React using TypeScript uses descriptive comments
  • TypeScript also involves the usage of hooks. It takes the value given by the useState hook. It also makes use of the useReducer hook to implement discriminated unions.

There are two types using which you can build your application using TypeScript. One is using the Parcel, another is the Webpack. You can use TypeScript with classes, functional components, and also with props.

Functional Component

import * as React from 'react';

const Count: React.FunctionComponent<{
  count: number;
}> = (props) => {
  return <h1>{props.count}</h1>;
};

export default Count;

This function is written to define object the structure of the props. It can also be done using the following:

interface Props {
  count: number;
}

const Count: React.FunctionComponent<Props> = (props) => {
  return <h1>{props.count}</h1>;
};

Read our article on – Custom Tab Bar in React Native using SVG, and D3-Shape

Class Component

Class components can be created by using TypeScript like –

import * as React from 'react';

import Count from './Count';

interface Props {}

interface State {
  count: number;
};

export default class Counter extends React.Component<Props, State> {
  state: State = {
    count: 0
  };

  increment = () => {
    this.setState({
      count: (this.state.count + 1)
    });
  };

  decrement = () => {
    this.setState({
      count: (this.state.count - 1)
    });
  };

  render () {
    return (
      <div>
        <Count count={this.state.count} />
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}

Default Props

By using default props, we can develop our code in TypeScript like –

import * as React from 'react';

interface Props {
  count?: number;
}

export default class Count extends React.Component<Props> {
  static defaultProps: Props = {
    count: 10
  };

  render () {
    return <h1>{this.props.count}</h1>;
  }
}

render () {
  return (
    <div>
      <Count />
      <button onClick={this.increment}>Increment</button>
      <button onClick={this.decrement}>Decrement</button>
    </div>
  )
}

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs.”

 

Read More

Django Basics and Structure

Django is an open-source, fully-featured Python-based framework initially released on 21 July 2005 by Django Software Foundation. This framework helps in building complex web apps by following MTV (Model Template Views) architectural patterns. Django primarily focuses on developing complex websites, also ensuring certain features such as reusability, pluggability, less code, less coupling, quicker development, and more. Django also provides an effective interface that allows users to manage admin controls such as create, read, delete and update. Some of the popular sites that utilize the Django framework are Instagram, The Washington Times, Disqus, Nextdoor, PBS (Public Broadcasting Service), Bitbucket, and Mozilla.

Why Django?

In an era where frameworks are abundantly available for web and app development, why does Django stand as an effective choice among the others? There are plenty of answers to this question. Let’s see some of them below.

Django is written in Python, which is a user-friendly and most-readable programmable language that makes it more suitable for web development. Django stands first because of the outstanding features it provides. While developing a website in Django, you don’t need to seek help from external packages or libraries, as working with Django syntax is seamless and makes you feel like using a single framework. Want to add some more features to enhance your website? Of course, you can use a variety of external libraries in Django.

Django’s in-depth documentation provides clear and detailed documentation about every feature of Django with great examples and tutorials.

Got stuck in the middle of your website development? Django provides an excellent community of developers for this, to whom you can ask for help either by document checking or by asking them.

Django Website’s Structure

A single project in Django will be divided into separate apps. Each app on the project manages separate functions of the website. Let’s say, if you are building a social app, it will consist of various functions to perform. It may have different functions like,

  • User Control: User-specific functionalities such as sign in, sign out, register, and more.
  • Feed Control: Feed related functions such as posting, displaying, commenting
  • Messaging: Private messages and notifications.

Above are the functions used by a typical social media app. If you are building this with Django, each of these functions will be a different app under a single project.

With Django, you can apply some configurations to the whole project. Some of the configurations include project settings, shared templates, URLs, and static files. Each application inside a project has its own database and can manage how the data should be displayed in HTML templates to the user. Apart from this, each application in a single Django project has its URLs, its HTML templates, and static files like JS and CSS.

Each application in Django is structured in a way that should provide a separation of logic. As mentioned earlier, it follows MVC architecture, on which most of the frameworks are developed.

Three files are in each application that controls the separation of logic into three main pieces. They are:

  • Model: It defines the data structure. It is the base layer and is the database of an application.
  • View: It displays the data with HTML and CSS to the users.
  • Controller: It controls how the view and database interact.

Though Django follows the MVC pattern, some of the properties in its architecture may slightly vary. Django manages the controller part on its own. Interaction between the database and views need not be defined and everything has been done already for you.

To know more about MVC, check out Model-View-Controller (MVC) Explained – With Legos.

The views of the MVT pattern which is used by Django have views and templates. You only need to add the URLs to map the views and Django manages the remaining works. Every Django website has a number of applications for handling separate functionalities and those applications follow the MVT pattern. This is the basic structure of a Django website.

Getting started with our First Django Project

We are going to discuss a simple project with Django. Before that, we have to set up the right plan of what we are going to build. Let’s build an app that has the following features:

  • Blog: A simple application can be created that lets you create, delete, sort, and update blog posts. Users can also comment on the blog posts.
  • Portfolio: You can also showcase your works like your previous projects and more.

Setting Up the Development Environment 

It is always better to set up the development environment before starting to build a website. A new directory for the live project can be created by,

$ mkdir rp-portfolio
$ cd rp-portfolio

Now you got into the main directory, the next step is to manage dependencies by creating a virtual environment. It can be created by,

$ python3 -m venv venv

Now, a folder called “venv” has been created in the working directory. You can now find several files along with the copy of standard libraries of Python inside the working directory. Whenever you are installing any new dependencies, you can find them to be stored in this working directory. The virtual environment can be activated by,

$ source venv/bin/activate

Users who don’t use bash shell need a comment

C:\> venv\Scripts\activate.bat

to activate the virtual environment.

Now you have activated your virtual environment and the control prompt in the terminal will look like,

(venv) $

Now install Django using pip,

(venv) $ pip install Django

Everything has been set up now, and you can start creating your first-ever project on Django.

Read our article on Data Visualization in Python using Matplotlib

Creating a Project

As we know, a Django app consists of a project and the constituent apps associated with it. After the successful creation of your virtual environment, run the command for project creation,

$ django-admin startproject personal_portfolio

This command creates a new directory named “personal portfolio” and almost all of the works you do will be saved into this directory.

After setting up the file structure, you can check whether your setup is successful or not by starting the server. To do this, run the command:

$ python manage.py runserver

You can now see your newly created Django site in your browser. Let’s see how to add views and functionalities to your site.

 

The first step is to create the app.

$ python manage.py startapp hello_world

Here, hello_world is the name of the new app we are going to create. This command will create a directory named hello_world consisting of several other files such as

  • __init__.py makes the Python consider the directory as a Python package.
  • admin.py consists of Django admin page settings.
  • apps.py consists of application configuration settings.
  • models.py consists of series of classes that make Django’s ORM convert to database tables.
  • tests.py consists of test classes.
  • views.py consists of classes and functions for handling the data displayed in HTML templates.

After the successful creation of the app, you have to install the app in your project. To do this, add the following code.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello_world',
]

Creating a view 

Django views are a set of classes or functions that are contained inside the views.py file. Whenever a URL is browsed, each class or function manages the logic that is processed. Add the following piece of code to the already available import render() code in the views.py file in the hello_world directory.

from django.shortcuts import render

def hello_world(request):
    return render(request, 'hello_world.html', {})

Here, we have defined a view named hello_world(). Upon function call, this will render the hello_world.html file. Now it is time to create templates inside the app directory.

$ mkdir hello_world/templates/
$ touch hello_world/templates/hello_world.html

The following HTML lines should be added to your file to get displayed:

<h1>Hello, World!</h1>

Now, a function for handling the views and templates for displaying it to the user has been created. The last step is to attach the URL which lets you see the page you have created.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('hello_world.urls')),
]

These commands check for a module named urls.py inside the hello_world app and register the URL defined inside that. For creating the hello_world.url,

$ touch hello_world/urls.py

Import path objects and the views module inside this module. Then a list of URL patterns for the corresponding view functions should be created.

from django.urls import path
from hello_world import views

urlpatterns = [

    path('', views.hello_world, name='hello_world'),
]

Now you can see your app when you visit localhost:8000. Success! We have created our first-ever Django project! This is a simple project created only with HTML. You can also add CSS styles or bootstrap styles to the project.

“We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs.”

Read More