How to write React function components in Typescript

Last updated on Nov 21, 2020 by Suraj Sharma



In this tutorial, you will learn two different ways to strongly type React function components in Typescript



1. Using Props Type


This is a straightforward approach to type function components in Typescript


type UserProps = {
    name: string
  age: number
}

const User = (props: UserProps) => {
  return (
    <>
      <p>{props.name}</p>
      <p>{props.age}</p>
    </>
  )
};

export default User;



You can also write a function component using React.FC or React.FunctionComponent


This is the most common and widely used approach to strongly type function components in React and Typescript


type AddressProps = {
    city: string
  country: string
}


const Address:React.FC<AddressProps> = (props) => {
  return (
    <>
      <p>{props.city}</p>
      <p>{props.country}</p>
    </>
  )
};

export default Address;


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.