Recently, I had this pull request that triggered a short discussion with my teammates. Someone noticed that I used a different method to write types for the function components I wrote, whereas there were other methods used in the codebase.

In this bite-sized React article, I’ll show you the right way to do it.

Function Components From a Type-Oriented Perspective

Functions, in general, are programmatic tools that take some input, process it, and return some output. Function components essentially work the same way. They take properties and convert them into UI elements. You can see below a super-basic function component example from using plain JavaScript.

function Welcome(props) {
	  return <h1>Hello, {}</h1>;
view raw
basic-react-fn-comp.js hosted with ❤ by GitHub

By rewriting this component with TypeScript, we aim to make sure that we

  • use the correct properties with their correct types
  • get a value of the correct type returned from the function

#reactjs #programming #typescript #javascript #react

The Right Way to Create Function Components in React With TypeScript
1.45 GEEK