DEV Community

Cover image for React Functional Components using TSX
John Peters
John Peters

Posted on

React Functional Components using TSX

Today I wanted to see how to create a React Functional Component using Typescript.

Here's the rules.

Typescript Functional Components

  • Function files must have a tsx suffix.
  • In that tsx file:
    • Import the type of FC and perhaps UseState hook.
// FC = Functional Component
import React, { FC, useState }
 from "react";
Enter fullscreen mode Exit fullscreen mode
  • Create a property prototype
// allows HTML binding to a title property
type props = {
  title: string;
}; 
Enter fullscreen mode Exit fullscreen mode
  • Create the function
const Test: FC<props> = ({ title }) => {
  const [hidden, setDisplay] = useState(false);
  function toggleVisibility() {
     hidden===true?setDisplay(false)
     :setDisplay(true);
  }

  return (
    <div>
      <h3 hidden={hidden}>{title}!</h3>
      <button onClick={toggleVisibility}>Toggle visibility</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Don't forget this part at the end of the file:

// Makes it a module
export default Test;
Enter fullscreen mode Exit fullscreen mode

Consumer
Import the component first:

import Test from "./fileName";
Enter fullscreen mode Exit fullscreen mode

Then use it like this:

    <Test title="Yes it works!"></Test> 
Enter fullscreen mode Exit fullscreen mode

For this simple example, we gain very little advantage for the effort.

This is all we gain on the caller side if we're looking for properties.

Alt Text

Alt Text

2.5 Stars for TSX

P.S.

  • TSConfig.json should look similar to this:
{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "strict": true,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "module": "es6",
        "moduleResolution": "node",
        "target": "es5",
        "allowJs": true,
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
    },
    "include": [
        "./src/**/*",
        "./src/public/**/*",
        "src/custom.d.ts"
    ]
}
Enter fullscreen mode Exit fullscreen mode

JWP2021 TSX

Top comments (0)