We're at Stripe

Sessions this week!

Fresh off being awarded Stripe's Services Implementation Specialization, we're in San Francisco to spend time with everyone. Make sure to say hi👋

Back

Convert a React Component to TypeScript

Joe Previte
Joe PreviteTuesday, January 7, 2020
The React framework icon with an arrow leading to the TypeScript programming language icon.

Converting a React component to TypeScript can be broken down in a few steps. Let’s walk through it together! Here’s the file we’ll use for our example:

import React from 'react' export const Header = ({text, color}) => { return <h1 style={{ color }}>{text}</h1> } Header.defaultProps = { color: 'red', text: 'Hello world!' }

1. Rename your file from .js or .jsx to .tsx

This tells React and TypeScript that this is a TypeScript/JSX file.

Header.jsx -> Header.tsx

2. Add a return type annotation and a type for your props

import React from 'react' type Props = { text: string; color: string; } export const Header: React.FC<Props> = ({text, color}) => { return <h1 style={{ color }}>{text}</h1> } Header.defaultProps = { color: 'red', text: 'Hello world!' }

React.FC stands for “Functional Component”. The <> is called a “generic” and it takes the interface/type for our component props. We define our props using atype.

3. Refactor your defaultProps to use ES6 default values

import React from 'react' type Props = { text: string; color: string; } export const Header: React.FC<Props> = ({text = 'Hello world!', color = 'red'}) => { return <h1 style={{ color }}>{text}</h1> }

Boom! You’re all done. Give yourself a pat on the back and dance. 🎉

Share this post

twitterfacebooklinkedin

Related Posts:

Interested in working with us?

Give us some details about your project, and our team will be in touch with how we can help.

Get in Touch