1567133042
Typescript is in its strongest position ever for making your React apps more stable, readable and manageable. The package has been steadily introducing more support for React and Javascript front-end frameworks; features have been ramping up specifically for them since version 3.0 and 3.1. Integration with React used to be a headache-inducing task, but is now a straight forward process that we will talk through in this article.
Create React App now has Typescript support built into the package, since react-scripts 2.1
. It can simply be included in a new project with the --typescript
flag. We will specifically be using CRA for bootstrapping a React based app with Typescript, before exploring how to integrate types and interfaces into React props and state, followed by a Redux setup.
To read more about Typescript, why it is used and its capabilities, take a look at my Typescript with NodeJS article, that aims to introduce the package and provide integration steps for NodeJS
The Create React App website has a dedicated page specifically for documenting the installation process as well as migration steps for adding Typescript support for existing apps. To create a new app with Typescript included, run the following:
yarn create react-app app_name --typescript#or
npx create-react-app app_name --typescript
There are a couple of noticeable changes from the Javascript based CRA boilerplate:
tsconfig.json
file configuring the Typescript compiler options..js
files are now .tsx
files. The Typescript compiler will pick up all .tsx
files at compile time.package.json
contains dependencies for @types packages, including support for node, jest, react and react-dom out of the box.react-app-env.d.ts
file to reference react-scripts
types. This file is automatically generated upon starting the development server, with yarn start
.Running yarn start
at this stage will compile and run your app, yielding the identical bootstrapped app in your browser to the original Javascript-only Create React App counterpart.
Before we continue, it is worth stopping the development server and revisiting some linting tools specifically for Typescript and React development. I will be focusing on Sublime Text 3 — being my IDE of choice — but the general concepts of linting apply to all IDEs. Let’s briefly explore the tools.
Installing TSLint-React
Installing linting tools are extremely helpful with Typescript and React; you will find yourself referring to tooltips to obtain a certain type, especially with events. The linting tools are extremely strict with their default setup, so we will omit some of these rules in the installation procedure.
Note: These tools are installed via NPM or Yarn and are not tied to a specific IDE. We will firstly install these tools before the specific packages for Sublime Text 3.
Install typescript
,tslint
and tslint-react
packages globally:
yarn global add tslint typescript tslint-react
Now inside your project directory, initialise tslint:
tslint --init
This command will generate a tslint.json
file with some default options. Replace this file with the following:
{
“defaultSeverity”: “error”,
“extends”: [
“tslint-react”
],
“jsRules”: {
},
“rules”: {
“member-access”: false,
“ordered-imports”: false,
“quotemark”: false,
“no-console”: false,
“semicolon”: false,
“jsx-no-lambda”: false
},
“rulesDirectory”: [
],
“linterOptions”: {
“exclude”: [
“config//*.js",
"node_modules//*.ts”
]
}
}
To summarise what is happening in this file:
defaultSeverity
is the level at which errors will be treated. error
being the default value will yield red errors within your IDE, whereas warning
would display orange warnings.“extends”: [“tslint-react”]
: The rules we are extending from are soley React based — we have removed the tslint-recommended
library, some rules of which do not adhere to React syntax.“rules”: { “rule-name”: false, …}
: We can omit rules in the rules
block. For example, omiting the member-access
rule will stop tslint from reporting that we are missing access types from our functions, (public, private…) — syntax that is not commonly used in React. Another example, ordered-imports
, prompts us to order our import statements alphabetically. Check out all the rules available here.“linterOptions”: {“exclude”: […]}
: Here we are excluding all Javascript files in the config
directory and Typescript files within node_modules
from TSLint checking.As the final step for setting up the development environment, install the SublimeLinter followed by SublimeLinter-tslint packages via PackageControl. Upon restarting Sublime Text the tools will be readily available.
Note: You may receive an error to say that the tslint module was not found upon restarting Sublime Text. If this was the case, re-install the packages locally rather than globally, that we opted for (and what documentation suggests) previously:
yarn add tslint tslint-react
VS Code Extension
For the Visual Studio Code editor, install the TSLint extension for full Typescript support.
With your IDE now ready to handle Typescript development, let’s dive into some code, visiting how to add interfaces and types to props and state within React.
We can apply interfaces and types for our props and state of our components.
Defining interfaces
Applying an interface
to components will force us to adhere to such data structures when passing props into a component, ensuring that they are all accounted for while also stopping unwanted props to be passed down.
Interfaces can be defined outside of a component or imported from a separate file. Define an interface like so:
interface FormProps {
first_name: string;
last_name: string;
age: number;
agreetoterms?: boolean;
}
Here I have created a FormProps
interface consisting of a few values. agreetoterms
is optional, hence the ?
after the name. We can also apply an interface for state:
interface FormState {
submitted?: boolean;
full_name: string;
age: number;
}
Note: Tslint used to prompt us to use a capital i in front of all our interface names, e.g. IFormProps and IFormState would be the above names. However, it is no longer enforced by default.
Applying interfaces to components
We can apply interfaces to both class components and stateless function components. For class components we utilise angle bracket syntax to apply our props and state interfaces respectively:
export class MyForm extends React.Component<FormProps, FormState> {
…
}
Note: In the event you have no props but would like to define state, you can place either {}
or object
in place of FormProps
. Both values are valid empty objects.
And with function components we can pass our props interface, followed by any other arguments and their specific interfaces:
function MyForm(props: FormProps) {
…
}
Importing interfaces
Defining groups of interface definitions in one file is good practice; a common convention is to create a src/types/
folder with groups of your interfaces:
// src/types/index.tsxexport interface FormProps {
first_name: string;
last_name: string;
age: number;
agreetoterms?: boolean;
}
And to import your needed interfaces into your component files:
// src/components/MyForm.tsximport React from ‘react’;
import { StoreState } from ‘…/types/index’;
…
Working with enums
Enums are another useful feature of Typescript. Lets say I wanted to define an enum
for the MyForm
component, and then check whether the submitted form value is valid:
// define enum
enum HeardFrom {
SEARCH_ENGINE = “Search Engine”,
FRIEND = “Friend”,
OTHER = “Other”
}
//construct heardFrom array
let heardFrom = [HeardFrom.SEARCH_ENGINE,
HeardFrom.FRIEND,
HeardFrom.OTHER];//get submitted form value
const submitted_heardFrom = form.values.heardFrom;//check if value is valid
heardFrom.includes(submitted_heardFrom)
? valid = true
: valid = false;
Working with iterables
We can also loop through iterables using for…of
and for…in
methods in Typescript. These two methods have one key difference:
for…of
will return a list of values being iterated.for…in
will return a list of keys being iterated.for (let i in heardFrom) {
console.log(i); // “0”, “1”, “2”,
}for (let i of heardFrom) {
console.log(i); // “Search Engine”, “Friend”, “Other”
}
Typing Events
In the event (no pun intended) you wish to type events, such as onChange
or onClick
events, utilise your syntax tools to obtain the exact event you need.
Consider the following example, where we update our state every time a name
input is changed. By hovering your mouse over handleChange()
, we can see clearly that the event type is indeed React.ChangeEvent<HTMLInputElement>:
Hovering over handleChange() to obtain the event type
This type is then used when typing the e
argument in our handleChange
function definition.
I have also typed the name
and value
objects of e
with the following syntax:
const {name, value}: {name: string; value: string;} = e.target;
If you do not know what types an object specifies, then you can simply use the any
type. We could have done this here:
const {name, value}: any = e.target;
Now we have covered some basics, we will next visit how to set up Redux with Typescript, and review more Typescript specific features along the way.
If you would like to familiarise yourself with how Redux works with React, check out my introductory article:
Step 1: Typing the Store
Firstly, we will want to define an interface
for our Redux store. Defining the expected state structure will be beneficial for your team and aid in maintaining the expected app state.
This can be done within the /src/types/index.tsx
file we discussed earlier. Here is an example that deals with locality and authentication:
// src/types/index.tsxexport interface MyStore {
language: string;
country: string;
auth: {
authenticated: boolean;
username?: string;
};
}
Step 2: Defining action types and actions
Action types can be defined using a const & type
pattern. We will firstly want to define the action types within a src/constants/index.tsx
file:
// src/constants/index.tsxexport const SET_LANGUAGE = ‘INCREMENT_ENTHUSIASM’;
export type SET_LANGUAGE = typeof SET_LANGUAGE;
export const SET_COUNTRY = ‘SET_COUNTRY’;
export type SET_COUNTRY = typeof SET_COUNTRY;
export const AUTHENTICATE = ‘AUTHENTICATE’;
export type AUTHENTICATE = typeof AUTHENTICATE;
Notice how the constants we just defined are used as an interface type andas a string literal, which we will utilise next.
These const & type
objects can now be imported into your src/actions/index.tsx
file, where we can define action interfaces and the actions themselves, and typing them along the way:
// src/actions/index.tsximport * as constants from ‘…/constants’;
//define action interfaces
export interface SetLanguage {
type: constants.SET_LANGUAGE;
language: string;
}
export interface SetCountry {
type: constants.SET_COUNTRY;
country: string;
}
export interface Authenticate{
type: constants.AUTHENTICATE;
username: string;
pw: string;
}
//define actions
export function setLanguage(l: string): SetLanguage ({
type: constants.SET_LANGUAGE,
language: l
});
export function setCountry(c: string): SetCountry ({
type: constants.SET_COUNTRY,
country: c
});
export function authenticate(u: string, pw: string): Authenticate ({
type: constants.SET_COUNTRY,
username: u,
pw: pw
});
Check out the authenticate
action in particular here — we are passing a username and password, both of which are of type string
, into the function. The return value is also typed, in this case as Authenticate
.
Within the Authenticate
interface we are also including the expected username
and pw
values for the action to be valid.
Step 3: Defining Reducers
To simplify the process of specifying an action type within a reducer, we can take advantage of union types, introduced in Typescript 1.4. A union type gives us the ability to combine 2 more more types into one type.
Back in our actions file, add a union type for locality under our interfaces:
// src/actions/index.tsxexport type Locality = SetLanguage | SetCountry;
Now we can apply this Locality
type to our locality reducer action, in bold text below:
// src/reducers/index.tsximport { Locality } from ‘…/actions’;
import { StoreState } from ‘…/types/index’;
import { SET_LANGUAGE, SET_COUNTRY, AUTHENTICATE} from ‘…/constants/index’;
export function locality(state: StoreState, action: Locality): StoreState {switch (action.type) {
case SET_LANGUAGE:
return return { …state, language: action.language};
case SET_COUNTRY:
return { …state, language: action.country};
case AUTHENTICATE:
return {
…state,
auth: {
username: action.username,
authenticated: true
}
};
}
return state;
}
This reducer is relatively straight forward, but nonetheless fully typed:
StoreState
, and the expected action as a Locality
type.StoreState
object, if only just the original state in the event no actions are matched.Step 4: Creating the initial Store
Now within your index.tsx
we can initiate the store, utilising angle brackets again to pass the type in conjunction with createStore()
:
// src/index.tsximport { createStore } from ‘redux’;
import { locality } from ‘./reducers/index’;
import { StoreState } from ‘./types/index’;
const store = createStore<StoreState>(locality, {
language: ‘British (English)’,
country: ‘United Kingdom’,
auth: {
authenticated: false
}
});
We are almost done — this covers most of our Redux integration. Let’s also visit mapStateToProps
and mapDispatchToProps
to cater for your container components.
Within mapStateToProps
, remember to map the state
argument with StoreState
. The second argument, ownProps
, can also be typed with a props interface:
// mapStateToProps exampleimport { StoreState } from ‘…/types/index’;
interface LocalityProps = {
country: string;
language: string;
}
function mapStateToProps (state: StoreState, ownProps: LocalityProps) ({
language: state.language,
country: state.country,
});
mapDispatchToProps
is slightly different; we are utilising angle brackets again to pass an interface into the Dispatch method. Then, as expected, the return block dispatches our Locality
type actions:
// mapDispatchToProps exampleconst mapDispatchToProps = {
actions.setLanguage,
actions.setCountry
}
Note: As we are wrapping these actions within connect()
, it is not required to wrap our actions within dispatch()
. We can also emit the parameters of our actions here.
Lastly, we can connect the two to our presentation component:
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
This article has introduced Typescript in conjunction with React and how to utilise tslint-react
for smoother development. We have visited how to interface and type your props and state throughout your components, as well as how to handle Typescript with events. Finally, we visited Typescript integration with Redux, integrating types throughout a Redux setup.
From here, you are now well placed to study the full feature set of Typescript in the official documentation.
Typescript does introduce additional consideration into your React projects, but the additional investment of supporting the language will ultimately improve the manageability of your apps as they scale.
Modularity and compartmentalising code is promoted by using Typescript; traits that medium to larger sized projects will want to adhere to. Keep this in mind as your projects grow: If you are finding maintainability a problem, Typescript could be the answer to improve readability while reducing the probability of errors throughout your codebase.
Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!
Originally published on medium.com
#reactjs #typescript #redux #javascript #web-development
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1602991640
Redux has become one of the most popular libraries in front-end development since it was introduced by Dan Abramov and Andrew Clark in 2015. They designed it as the successor for Flux, with the support of some developer tools and a few more concepts embedded in it.
Flux is a fancy name for observer pattern further modified to support React. Both Flux and Redux consist of similar concepts like Store, Actions (events in the application). In other words, Flux is a simple JavaScript object but with some middleware like redux-thunk. It can be a function or a promise for Redux. However, Redux is a single source of truth with concepts like immutability, which improve performance. It is one of the main reasons for Redux to dominate in State Management.
Flux vs Redux comparison source: enappd.com
Despite its advantages, some developers have found it rather challenging to deal with Redux due to the amount of boilerplate code introduced with it. And the complexity of the code seems to be another reason for the difficulty.
In this article, we will look at how to reduce the boilerplate code brought about by Actions and Reducers using Redux-Actions
#react-redux-boilerplate #react-redux #react #react-actions #redux
1599666780
Wanted to make a video with redux and redux-thunk using typescript. I found this a bit confusing when I first learned it and hopefully this videos makes the topic a bit easier to understand for you. If you have any questions leave a comment and ill be sure to respond and give you a hand.
Github Source Code: https://github.com/daryanka/typescript-with-redux
#redux #typescript #typescript #react #javascript
1601294220
React Native Redux Example | How To Use Redux In React Native is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React.
The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy, whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.
We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed it.
#react native #react native cli #react native on mac #redux #react developer
1626367740
Hello! In this series we will learn how to use Redux to manage the state of your app. We will use TypeScript and ReactJS to build simple shopping cart app. My aim is to explain how you can build app with Redux in 2021 with the latest and the best patterns. We will use hooks and slices as our approach to build our store and connect Redux to our ReactJS app.
In the second episode we will discuss Redux basics, create our store, link it to ReactJS and write our first Redux slice.
You can find me here:
https://twitter.com/wojciech_bilick
https://medium.com/@wojciech.bilicki
https://github.com/wojciech-bilicki
ignore
web design
html
web development
css
html5
css3
es6
programming
basics
tutorial
javascript
how to make a website
responsive design tutorial
web development tutorial
media queries
website from scratch
html css
responsive website tutorial
responsive web development
web developer
how to make a responsive website
how to build a website from scratch
how to build a website
build a website
How to
#react #redux #typescript #redux