Friday 6 October 2017

React & Webpack Example


1. React & Webpack Example found from this url: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html


2. Code of React & Webpack Example

import * as React from "react";

class HelloParent extends React.Component<{}, {}> {
    constructor(prop) {
        //call parent class constructor
        super(prop);
    }

    private onNameChange(name) {
        console.log(name);
        //call child method from parent
        this.hellComponet.callByParent("BillTo");
    }
    hellComponet: any;

    render() {
        return (<Hello ref={instance => { this.hellComponet = instance; }} name="Willson" onNameChange={this.onNameChange} />);
    }

}

interface HelloProps {
    name: string;
    onNameChange: (name: string) => void;
}

interface HelloState {
    name: string;
}

class Hello extends React.Component<HelloProps, HelloState> {
    constructor(prop) {
        //call parent class constructor
        super(prop);

        //Define State
        this.state = {
            name: "A"
        }

        //set State
        this.setState({ name: "B" });

        //call parent class method from child
        this.props.onNameChange(this.state.name);

        //Bind the functions
        this.callByParent = this.callByParent.bind(this);
    }

    componentWillMount() {

        //async call by the typescript promise
        let promises: Array<Promise<any>> = [];
        this.getMethod("", "", null, "", null, null, promises);

        //Core js Promise resolve all call.
        Promise.all(promises).then(() => { });

    }

    private getMethod(url: string, baseUrl: string, headers: Array<string>, method: string, body: any, parser: any, promises: Promise<any>[]): void {
        promises.push(
            fetch((url.indexOf("http") == 0 ? url : baseUrl + url), {
                credentials: 'same-origin',
                headers: headers,
                method: method,
                body: typeof body == "string" ? body : JSON.stringify(body)
            }).then(parser)
        );
    }

    public callByParent() {

    }

    render() {
        return <div>Hello, {this.props.name}</div>;
    }

}

export default Hello;