File tree Expand file tree Collapse file tree 1 file changed +18
-5
lines changed Expand file tree Collapse file tree 1 file changed +18
-5
lines changed Original file line number Diff line number Diff line change @@ -14,31 +14,44 @@ import SEO from '../../components/Seo';
1414
1515# Functional Components
1616
17- Given that functional components are just functions that take in props as a parameter, we can do the following:
17+ Use the ` React.FC ` type and define the generic with your props type.
1818
1919``` typescript
2020type HelloWorldProps = {
2121 userName: string ;
2222};
2323
24- const HelloWorld = ({ userName }: HelloWorldProps ) => (
25- <div >Hello , {userName }! < / div >
24+ const HelloWorld: React .FC <HelloWorldProps > = ({ children , userName }) => (
25+ <div >
26+ <p >Hello , {userName }< / p >
27+ {children }
28+ < / div >
2629);
2730```
2831
29- However, this does not take the ` children ` prop into account. Use the ` React.FC ` type and define the generic as your props type.
32+ ## Functional Components with "Static" Properties
33+
34+ If you need to use a "static" property with your functional component (say, to define a router), you can do the following:
3035
3136``` typescript
37+ type Router = {
38+ route: string ;
39+ };
40+ const someFancyRouter: Router = { route: ' /hello/world' };
41+
3242type HelloWorldProps = {
3343 userName: string ;
3444};
3545
36- const HelloWorld: React .FC <HelloWorldProps > = ({ children , userName }) => (
46+ type HelloWorldComponent = React .FC <HelloWorldProps > & { router: Router };
47+
48+ const HelloWorld: HelloWorldComponent = ({ children , userName }) => (
3749 <div >
3850 <p >Hello , {userName }< / p >
3951 {children }
4052 < / div >
4153);
54+ HelloWorld .router = someFancyRouter ;
4255```
4356
4457[ This video] ( https://www.youtube.com/watch?v=9lUN3sqAjQQ ) explains another example of typing a functional component.
You can’t perform that action at this time.
0 commit comments