Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Render a React Component with State and Props using TypeScript

Jul 3, 2020 • 7 Minute Read

Introduction

Writing components in TypeScript that contain both props as well as a state is one of the core tasks needed to build apps. Though both Functional and Class Components can contain props and a state, this guide will cover how to create and render a Class Component.
This is useful when migrating the React Class Components to TypeScript or writing them from scratch.

Use Case

Consider a web page that displays famous quotes on the screen and a button that renders a new quote when clicked. This functionality requires a component to have both props and state. A collection of quotes will be passed in props and state. The component tracks the current quote being displayed on the screen.

Set Up a React TypeScript App

Open your terminal and run these commands to get a sample TypeScript app running on your machine.

      npx create-react-app my-app --template typescript
cd my-app
yarn start
    

To run the app in development mode, open https://localhost:3000 in your browser. You should see the sample TypeScript app running.

Add QuoteApp Component

Delete the App.tsx file inside your src directory. Now create a new component src/QuoteApp.tsx and add the code below.

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

type QuoteProps = {
    quotes: string[]
}

type QuoteState = {
    currentIndex: number,
}

export default class QuoteApp extends React.Component<QuoteProps, QuoteState> {

    render() {
        return <div className="App">
            <header className="App-header">
                <h3>Render Component with State and Props using TypeScript</h3>
            </header>
        </div>
    }
}
    

In the code above, <QuoteApp> is a Class Component and in TypeScript, React.Component is defined as a generic type with two optional type parameters. The first one is for prop type and the second for the state type.

QuoteProps is the type defined for the props allowed in the <QuoteApp> component. The caller of the <QuoteApp> component should pass an array of strings in props containing the quotes to display. QuoteState is the type defined for the state of the <QuoteApp> component. It contains the currentIndex of type number. This is the current index of the quote being rendered from the collection. Inside the render() function a <div> is returned that displays a header on the web page with the header text rendered inside an <h3> element.

Render Component Using State and Props

It's time to display the quote on the web page and a button so that users can click on it. The code below would do the job. The <QuoteApp> component has a state of type QuoteState with an initial value for currentIndex as zero. When the component is called with props quotes (an array of strings), the quoteToDisplay variable gets the element at currentIndex from that array and renders it. The <div> element contains inline styles to give it an appropriate alignment and the quote is displayed inside an HTML heading, <h4>.

A <button> is added with a label "NEXT QUOTE". When user clicks on this button, the getNextQuote() function is called. It returns void and update the state with a new value of currentIndex. It also calls getIndex() function whose job is to return a random number between zero and the last index of the quotes array.

In a nutshell, when a user clicks on the NEXT QUOTE button, the getNextQuote() function gets a new value for the index by calling getIndex() function. Once the currentIndex value is updated, the quote at that index is rendered.

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

type QuoteProps = {
    quotes: string[]
}

type QuoteState = {
    currentIndex: number,
}

export default class QuoteApp extends React.Component<QuoteProps, QuoteState> {
    state: QuoteState = {
        currentIndex: 0,
    };

    getIndex = (): number => {
        const min: number = 0;
        const max: number = this.props.quotes.length - 1;
        return Math.floor(Math.random() * (max - min) + min);
    };

    getNextQuote = (): void => this.setState(state => ({currentIndex: this.getIndex()}));

    render() {
        const quoteToDisplay = this.props.quotes[this.state.currentIndex];
        return <div className="App">
            <header className="App-header">
                <h3>Render Component with State and Props using TypeScript</h3>
            </header>
            <div style={{height: "5vh", padding: "1em", margin: "7em"}}>
                <h4>{quoteToDisplay}</h4>
            </div>
            <button onClick={this.getNextQuote}>NEXT QUOTE</button>
        </div>
    }
}
    

Call QuoteApp Component

Now <QuoteApp> component is ready to be called. All it needs is an array of quotes. Go to your src/index.tsx file and replace the code in that file with this code.

randomQuotes is an array of strings containing quotes. <QuoteApp> component is called with a prop quotes and its value randomQuotes.

Go to the browser and open https://localhost:3000. You should a quote rendered on the screen, it is the quote at index zero in the quotes array. Each time you click on the button, it displays a new quote.

      import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import QuoteApp from './QuoteApp';
import * as serviceWorker from './serviceWorker';

const randomQuotes: string[] = [
    "Before you judge a man, walk a mile in his shoes. After that who cares?... He’s a mile away and you’ve got his shoes!",
    "Better to remain silent and be thought a fool than to speak out and remove all doubt.",
    "The best thing about the future is that it comes one day at a time.",
    "The only mystery in life is why the kamikaze pilots wore helmets.",
    "Light travels faster than sound. This is why some people appear bright until you hear them speak.",
    "The difference between stupidity and genius is that genius has its limits"
]
ReactDOM.render(
    <React.StrictMode>
        <QuoteApp quotes={randomQuotes}/>
    </React.StrictMode>,
    document.getElementById('root')
);
serviceWorker.unregister();
    

Code on GitHub

You can access the entire code for this example on GitHub

Conclusion

You learned how to render a Class Component with state and props using TypeScript. In this code example, we used type alias to declare the prop and state types QuoteProps and QuoteState. This is because both QuoteProps and QuoteState are simple object type literals and strictly constrain the structure of these objects. But you can also make use of TypeScript interface for QuoteProps if there is need of implementing or extending that interface in the code.