MoinMoin Logo
  • Comments
  • Immutable Page
  • Menu
    • Navigation
    • RecentChanges
    • FindPage
    • Local Site Map
    • Help
    • HelpContents
    • HelpOnMoinWikiSyntax
    • Display
    • Attachments
    • Info
    • Raw Text
    • Print View
    • Edit
    • Load
    • Save
  • Login

Navigation

  • Start
  • Sitemap

Upload page content

You can upload content for the page named below. If you change the page name, you can also upload content for another page. If the page name is empty, we derive the page name from the file name.

File to load page content from
Page name
Comment

Revision 12 as of 2026-08-23 15:37:49
  • react

Contents

  1. react
    1. webpack.config.js
    2. tsconfig.json
    3. lib.ts
    4. greeter.html
    5. package.json
    6. App.tsx
    7. greeter.tsx
    8. NameHolder.tsx
    9. build.sh
    10. TypeDI
    11. axios
    12. tsoa

react

https://reactjs.org/ https://react.dev/

A Javascript library for building user interfaces.

Build encapsulated components that manage their own state, then compose them to make complex UIs.

https://reactjs.org/docs/thinking-in-react.html

The main component react methods are:

  • render
  • componentWillUnmount
  • componentDidMount

We can set XML node properties for the component and properties for its inner state. The component also allow inner children.

Structure

   1 .
   2 ├── App.tsx
   3 ├── build.sh
   4 ├── greeter.html
   5 ├── greeter.tsx
   6 ├── lib.ts
   7 ├── NameHolder.tsx
   8 ├── package.json
   9 ├── tsconfig.json
  10 └── webpack.config.js

webpack.config.js

   1 var path = require('path');
   2 
   3 module.exports = {
   4   entry: {main:'./greeter.js'},
   5   resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
   6   output: {
   7     filename: 'bundle.js',
   8     path: path.resolve(__dirname, 'dist')
   9   }
  10 };

tsconfig.json

   1 {
   2     "compilerOptions": {
   3         "module": "es2015",
   4         "target": "es5",
   5         "noImplicitAny": true,
   6         "removeComments": true,
   7         "preserveConstEnums": true,
   8         "sourceMap": true,
   9         "moduleResolution": "node",
  10         "allowSyntheticDefaultImports": true,
  11         "jsx": "react"
  12     }
  13 }

lib.ts

   1 function getText() {
   2     return "text";
   3 }
   4 
   5 interface Person {
   6     firstName: string;
   7     lastName: string;
   8 }
   9 
  10 function greeterPerson(p: Person) {
  11     return "Hello GP, " + p.firstName + ' ' + p.lastName + ' ' + getText();
  12 }
  13 
  14 function greeter(person: string) {
  15     return "Hello, " + person;
  16 }
  17 
  18 interface HumanInterface {
  19     name: string;
  20     getName(): void;
  21 }
  22 
  23 class Human implements HumanInterface {
  24     name: string;
  25 
  26     constructor(name: string) {
  27         this.name = name;
  28     }
  29 
  30     getName() {
  31         return "My name is " + this.name;
  32     }
  33 }
  34 
  35 class PubSub {
  36     callbacks: Function[];
  37 
  38     constructor() {
  39         this.callbacks = [];
  40     }
  41 
  42     addListener(fn: Function): void {
  43         this.callbacks.push(fn);
  44     }
  45 
  46     notify(message: string): void {
  47         this.callbacks.forEach((fn) => {
  48             fn(message);
  49         });
  50     }
  51 }
  52 let pubSub = new PubSub();
  53 
  54 export { greeter, greeterPerson, Human, HumanInterface, Person, getText, PubSub, pubSub }

greeter.html

   1 <!DOCTYPE html>
   2 <html>
   3     <head><title>React + typescript test</title><meta charset="UTF-8"></head>
   4     <body>        
   5         <div id="app"></div>
   6         <script src="dist/bundle.js"></script>
   7     </body>
   8 </html>

package.json

   1 {
   2   "name": "test",
   3   "private": true,
   4   "version": "0.0.0",
   5   "devDependencies": {
   6     "@types/react": "15.0.35",
   7     "@types/react-dom": "15.5.1",
   8     "@types/webpack-env": "1.13.0",
   9     "react": "15.6.1",
  10     "react-dom": "15.6.1",
  11     "typescript": "2.4.1",
  12     "webpack": "2.5.1"
  13   }
  14 }

App.tsx

   1 import React, { ReactChild } from 'react';
   2 import { Persn, greeterPerson, Human, HumanInterface } from './lib';
   3 import NameHolder from './NameHolder';
   4 import { pubSub } from './lib';
   5 
   6 interface MyState {
   7     currDate: string;
   8     greetings: string;
   9     human: HumanInterface;
  10 }
  11 
  12 function createMyState(currDate: string, greetings: string, human: HumanInterface): MyState {
  13     return { currDate: currDate, greetings: greetings, human: human };
  14 }
  15 
  16 interface MyProps {
  17     prop: string;
  18 }
  19 
  20 export default class App extends React.Component<MyProps, MyState> {
  21     text: string;
  22     timerID: number;
  23 
  24     constructor(props: MyProps) {
  25         super(props);
  26         this.text = this.props.prop;
  27         this.state = createMyState("waiting for date", "waiting for greetings", null); // init with MyState format          
  28     }
  29 
  30     public static createHuman(name: string): HumanInterface {
  31         return new Human(name);
  32     }
  33 
  34     public tickHandler() {
  35         let cd = new Date().toString();
  36         let greetings = greeterPerson({ firstName: "first", lastName: "last" });
  37         let human: HumanInterface = App.createHuman("JohnDoe");
  38         this.setState(createMyState(cd, greetings, human));
  39     }
  40 
  41     componentDidMount() {
  42         // called after the 1st render !
  43         console.log("First render");
  44         this.timerID = setInterval(this.tickHandler.bind(this), 1000);
  45     }
  46 
  47     componentWillUnmount() {
  48         // component will be destroyed
  49         console.log("Will be destroyed soon");
  50         clearInterval(this.timerID);
  51     }
  52 
  53     public render() {
  54         // do not call set state in render !
  55         return (
  56             <div>
  57                 <p>Hello World!!! -- {this.text} -- {this.state.greetings}</p>
  58                 <p>Human {this.state.human != null ? this.state.human.getName() : ""} {this.state.currDate} </p>
  59 
  60                 <p> <NameHolder attr="holding..." />  </p>
  61                 <p> <NameHolder attr={this.state.currDate} /> </p>
  62 
  63                 <div onClick={() => { this.clickHandler(); }} > {this.props.children} </div>
  64             </div>
  65         );
  66     }
  67 
  68     public clickHandler() {
  69         console.log("clicked. # children " + React.Children.count(this.props.children));
  70 
  71         React.Children.forEach(this.props.children, (argx: any) => {
  72 
  73             if (argx.hasOwnProperty("props")) {
  74                 console.log("props property found");
  75                 pubSub.notify("message from outer space !");
  76             }
  77 
  78             console.log(JSON.stringify(argx));
  79         });
  80     }
  81 }

greeter.tsx

   1 import React from 'react';
   2 import ReactDOM from 'react-dom';
   3 import {getText} from "./lib";
   4 import App from './App'; // uses App.tsx
   5 import NameHolder from './NameHolder'; 
   6 
   7 console.log("Entry point");
   8 let appContainer =  document.getElementById('app') ;
   9 let markup = <App prop="Other text inside the page"> <NameHolder attr="NameHolder child inside App "/> </App>;
  10 ReactDOM.render( markup , appContainer);

NameHolder.tsx

   1 import React from 'react';
   2 import { pubSub } from './lib';
   3 
   4 // Component properties (XML attributes)
   5 interface NameHolderProperties {
   6     attr: string;
   7 }
   8 
   9 interface NameHolderState {
  10     attr: string;
  11 }
  12 
  13 // properties and state 
  14 export default class NameHolder extends React.Component<NameHolderProperties, NameHolderState> {
  15     constructor(props: NameHolderProperties) {
  16         super(props); // populates the this.props         
  17         this.state = { attr: this.props.attr };
  18 
  19         pubSub.addListener(this.onMessage);
  20     }
  21 
  22     public render() {
  23         return <span>!!!{this.state.attr}!!!</span>;
  24     }
  25 
  26     public onMessage(message: string): void {
  27         console.log(this.state.attr + " receiVed " + message);
  28     }
  29 }

build.sh

   1 PATH=$PATH:./node_modules/typescript/bin
   2 echo Delete dist folder
   3 rm -rf dist
   4 echo Install NPM packages
   5 npm install
   6 echo Compile project
   7 tsc
   8 echo Create application bundle
   9 nodejs ./node_modules/webpack/bin/webpack.js --config webpack.config.js

TypeDI

  • https://www.npmjs.com/package/typedi

TypeDI is a dependency injection tool for TypeScript and JavaScript. With it you can build well-structured and easily testable applications in Node or in the browser.

   1 import { Container, Service } from 'typedi';
   2 
   3 @Service()
   4 class ExampleInjectedService {
   5   printMessage() {
   6     console.log('I am alive!');
   7   }
   8 }
   9 
  10 @Service()
  11 class ExampleService {
  12   constructor(
  13     // because we annotated ExampleInjectedService with the @Service()
  14     // decorator TypeDI will automatically inject an instance of
  15     // ExampleInjectedService here when the ExampleService class is requested
  16     // from TypeDI.
  17     private injectedService: ExampleInjectedService
  18   ) {}
  19 }
  20 
  21 const serviceInstance = Container.get(ExampleService);
  22 // we request an instance of ExampleService from TypeDI
  23 
  24 serviceInstance.injectedService.printMessage();
  25 // logs "I am alive!" to the console
  26 

axios

  • https://www.npmjs.com/package/axios

Promise based HTTP client for the browser and node.js

   1 import axios from 'axios';
   2 //const axios = require('axios'); // legacy way
   3 
   4 try {
   5   const response = await axios.get('/user?ID=12345');
   6   console.log(response);
   7 } catch (error) {
   8   console.error(error);
   9 }
  10 
  11 // Optionally the request above could also be done as
  12 axios
  13   .get('/user', {
  14     params: {
  15       ID: 12345,
  16     },
  17     timeout: 5000, // 5 seconds. See "Handling Timeouts" below for matching error handling
  18   })
  19   .then(function (response) {
  20     console.log(response);
  21   })
  22   .catch(function (error) {
  23     console.log(error);
  24   })
  25   .finally(function () {
  26     // always executed
  27   });
  28 
  29 // Want to use async/await? Add the `async` keyword to your outer function/method.
  30 async function getUser() {
  31   try {
  32     // Example: GET request with query parameters
  33     const response = await axios.get('/user', {
  34       params: {
  35         ID: 12345,
  36       },
  37     });
  38 
  39     // Using the `params` option improves readability and automatically formats query strings
  40 
  41     console.log(response);
  42   } catch (error) {
  43     console.error(error);
  44   }
  45 }

tsoa

  • https://www.npmjs.com/package/tsoa

OpenAPI-compliant REST APIs using TypeScript and Node

  • https://tsoa-community.github.io/docs/getting-started.html

  • MoinMoin Powered
  • Python Powered
  • GPL licensed
  • Valid HTML 4.01