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";
- Create a property prototype
// allows HTML binding to a title property
type props = {
title: string;
};
- 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>
);
};
Don't forget this part at the end of the file:
// Makes it a module
export default Test;
Consumer
Import the component first:
import Test from "./fileName";
Then use it like this:
<Test title="Yes it works!"></Test>
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.
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"
]
}
JWP2021 TSX
Top comments (0)