How to write React function components in Typescript

#react #typescript

Last updated on Jan 3, 2021 by Suraj Sharma



In this tutorial, you're going to 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



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.