By Oct 02, 2019

Description:

We explain here how to create a React application with TypeScript and we give several examples of components with Props and State.

Preferencesoft

Creating a React application with TypeScript

Installing React

The installation of React is facilitated by node.js which allows to obtain all the packages necessary for the development.

Installation with Visual Studio is more immediate, and you can follow the approach to the following address:

https://docs.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs-with-react-and-jsx?view=vs-2017

We will, in the following, detail the installation with Visual Studio Code on Windows.

We assume that VSC and node.js are already installed on the operating system.

Let's first install create-react-app. In VS Code, let's open Poweshell and type the command:

npm Install -g create-react-app

Then in the main directory (projects) create a new application named reactts01. For this type the command:

create-react-app reactts01 --scripts-Version = react-scripts-ts

After the application is created, we can add the new directory to the current VS Code project.

Let's go to the reactts01 directory and launch the command:

npm run start

The application launches in the browser showing a logo and a welcome message.

React screen shot

The main part of the program is in the TSX file App.tsx (in the src directory)

App.tsx:

import * as React from 'react';
import './App.css';

import logo from './logo.svg';

class App extends React.Component {
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

TSX is a preprocessor whose language, based on TypeScript, can include XML elements.

At the pre-compilation, the TSX is transformed into pure TypeScript.

In this program, a new App class deriving from React.Component is declared. The Render method returns the components that makes up the App, to the rendering engine for display.

In fact, App is a new component that is used by default in index.tsx.

We will be interested in programming in TSX and add components to the automatically created application.

Creating a component

Much like in a building game, React allows developers to create new components from other components or HTML elements.

To create a TSX component, a class is derived from React.Component and the Render method is added. This method returns the XML code representing the component to be visualized.

We will create our first component and insert it into the application. This component is an OK button that displays Click when pressed.

App.tsx:

import * as React from 'react';
import './App.css';
import './Button.css';

import logo from './logo.svg';

class NumButton extends React.Component<any, any> {
  public render() {
    return (
      <button className="NumButton" onClick = {() => alert("Click")}>OK</button>
    );
  }
}

class App extends React.Component {
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
        <NumButton />
      </div>
    );
  }
}

export default App;

button.css:

.NumButton {
  background-color: blueviolet;
  height: 75px;
  width: 150px;
  padding: 10px;
  color: white;
  font-size: 24px;
}

Suppose we wanted to use this component in several different places but with a different text. To do this, it is possible to add to the component properties called props.

To define properties of a component, a constructor with the props parameter is added to the declaration of the class and we declare an interface containing the properties of the component.

App.tsx:

import * as React from 'react';
import './App.css';
import './Button.css';

import logo from './logo.svg';

interface INumButtonContentProps {
  text: string;
}

class NumButton extends React.Component<INumButtonContentProps, any> {
  constructor(props: INumButtonContentProps){
    super(props);
}

  public render() {
    return (
      <button className= "NumButton" onClick = {() => alert("text: "+this.props.text)}>
        {this.props.text}
      </button>
    );
  }
}

class App extends React.Component<any, any> {
  constructor(props: any){
    super(props);
}
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
        <NumButton text="Hello"/>
        <NumButton text="------"/>
        <div>
    </div>
      </div>
    );
  }
}

export default App;

Give the text property a default initial value:

App.tsx:

import * as React from 'react';
import './App.css';
import './Button.css';

import logo from './logo.svg';

interface INumButtonContentProps {
  text: string;
}

class NumButton extends React.Component<INumButtonContentProps, any> {
  constructor(props: INumButtonContentProps){
    super(props);
}

public static defaultProps: Partial<INumButtonContentProps> = {
  text: "OK"
};

  public render() {
    return (
      <button className= "NumButton" onClick = {() => alert("text: "+this.props.text)}>
        {this.props.text}
      </button>
    );
  }
}

class App extends React.Component<any, any> {
  constructor(props: any){
    super(props);
}
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
        <NumButton text="Hello"/>
        <NumButton/>
        <div>
    </div>
      </div>
    );
  }
}

export default App;

Now use a State, to be able to modify the text of the button each time the button is pressed. We cannot use properties, since they are not modifiable. As for properties, we declare an interface containing the Sates of the component.

App.tsx:

import * as React from 'react';
import './App.css';
import './Button.css';

import logo from './logo.svg';

interface INumButtonContentState {
  text: string;
}

class NumButton extends React.Component<any, INumButtonContentState> {

public state: INumButtonContentState = {
  text: "+"
};

 public concat = () => {
  const txt : string = this.state.text+"+";
  this.setState({text: txt});
};

  public render() {
    return (
      <div>
      <button className= "NumButton" onClick = {() => {this.concat();alert("text: "+this.state.text);}}>
        {this.state.text}
      </button>
      <p>Button content: {this.state.text}</p>
      </div>
    );
  }
}

class App extends React.Component<any, any> {
  constructor(props: any){
    super(props);
}
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
        <NumButton/>
        <div>
    </div>
      </div>
    );
  }
}

export default App;

Props

Props are properties that characterize a component. They are received from a parent component at initialization and are immutable. A component cannot change these properties, but it can communicate them to its son components.

State

The State is a data structure, receiving an initial value when creating the component, and used by it to store information over time. The State is a mutable variable that has a scope limited to the class of the component, in which data is often stored after a user event.


TypeScript

Categories

Share

Follow


KodFor Privacy Policy