Skip to content

Commit f80e103

Browse files
Aryan JabbariAryan Jabbari
authored andcommitted
Example of a "static" property with a React FC
1 parent 9dc3a09 commit f80e103

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/pages/examples/functional-components.mdx

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff 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
2020
type 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+
3242
type 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.

0 commit comments

Comments
 (0)