Thursday, August 13, 2020

React TypeScript component with State and Events

In the previous post we saw on how to do a simple Hello World application in React with TypeScript using the create-react-app package. In this post we will move on the next step we will add state support and event handling (button click event and text change event) to the component.

The React component initializes state, notice that we are using the State interface with strongly types properties to define the state object, this is the advantage of TypeScript it allows us to define strongly typed properties which help us capture type errors during development. The state object has 2 properties message and name.
import * as React from 'react';

interface State {
    message: string;
    name: string;
};

export default class Home extends React.Component {
  state: State = {
    name : "",
    message: ""
  };

  handleChange = (event : any) => {
    const { value } = event.target;
    this.setState(() => {
      return {
        name : value
      };
    });
  }

  SetGreeting = () => {
    this.setState({
        message: (`Hello ${this.state.name}, Welcome to React`)
    });
  };

  render () {
    return (
      <div className="container">
          <div className="row">
                <div className="col-md-4"> </div>
           </div> 
          <div className="jumbotron">                    
            <div className="row">
                <div className="col-md-4">
                    <input type="text"
                        onChange={this.handleChange}
                        value={this.state.name} />  
                    <button onClick={this.SetGreeting}
                        className="btn btn-sm btn-primary">Click</button>
                </div>
            </div>  
            <div className="row">
                <div className="col-md-4"> </div>
            </div>                 
            <div className="row">
                <div className="col-md-4">
                    <h5>{this.state.message}</h5>                
                </div>
            </div>   
          </div>             
      </div>
    );
  }
}

The component has a textbox and a button, we handle the onChange event of the textbox set the value in the name state property. We capture the onClick event of the button and set a greeting text in the message state object, this message is displayed in the screen.

Run the application using the npm start command, the output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: