You can create a stateless React component in TypeScript as easily as creating a function.
But if you want to create high quality idiomatic React + TypeScript components we cover some improved patterns in this lesson.
Basarat Ali Syed: [00:00] Here, I have a simple TypeScript application that renders the div Hello World! To the DOM using React and ReactDOM. We can easily move this div into a stateless component called App by creating a function called App and returning the same JSX element.
[00:24] Of course, one big advantage of components is that you get to use props that change the component behavior. For example, we can take the message as a prop by adding it as an argument and using it inside the function body. TypeScript tells us that this property needs to be provided, so we go ahead and provide it.
[00:45] Let's add something different this time. You can see that it works as expected. Although such simple functions work fine for stateless components, if you want to create high-quality types of components, it is recommended that you annotate such functions as React SFC.
[01:04] The React SFC interface takes a generic argument that allows you to easily provide the type annotation for the component props. You can see that the type specified over here flows through to the function arguments.
[01:21] Of course, if you want, you can easily move out this inline prop type definition into an appropriately named type, for example, App Props.
Can we create a type like
type someProps = { compiler: string, framework: string }
const App: React.FC<someProps> = (props) => { return ( <div> <div>{props.compiler}</div> <div>{props.framework}</div> </div> ); }
Yes Sarmad:
type SomeProps = { compiler: string, framework: string }
const App: React.FC<SomeProps> = (props) => {
return (
<div>
<div>{props.compiler}</div>
<div>{props.framework}</div>
</div>
);
}
React.SFC is
deprecated
now. Use : https://github.com/basarat/react-typescript/blob/master/src/app/app.tsx