4 Change State Program in ReactJS using TypeScript

src/State.tsx: 
  
import React, {Component} from "react";

interface IState{
    "sub": string;
};

interface IProps{};


class State extends Component<IProps,IState>{
    constructor(props:IProps){
        super(props);

        this.state={
            sub: "ReactJS"
        };
    };

    myFun = ()=>{
        this.setState({
            sub: "ReactJS with TypeScript"
        })
    };

    render(){
        return(
            <React.Fragment>    
                <h1> {this.state.sub} </h1>
                <button onClick={this.myFun}> Change </button>
            </React.Fragment> 
        );
    };
};

export default State;


src/index.tsx: 
  
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import State from "./State";

ReactDOM.render(
  <React.StrictMode>
    <State />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();



Output Original: 
setState() example

Output After Click: 
setState() example
Previous
Next Post »