Reputation: 349
In React, it seems that I can declare a functional component or just a function returns a JSX element. What confusing me is I don't know the key difference between these two approaches. Is there anything only one approach can do while another can not?
import React from "react";
type ItemProps = {
id: number
name: string
}
const Item: React.FC<ItemProps> = ({ id, name }) =>
(
<section>
my id is {id}
my name is {name}
</section>
)
const item = ({ id, name }: ItemProps) =>
(
<section>
my id is {id}
my name is {name}
</section>
)
export const Container = () =>
(
<section>
{item({ id: 1, name: "item-1" })}
<Item id={1} name={"item-1"} />
</section>
)
Upvotes: 34
Views: 35750
Reputation: 13882
children
prop, which means even if your component does not allow children, typescript would not complain if you are using React.FC
and the parent passes a children. This does not impact anything at the runtime, but it is better to be more explicit about the children prop. This might be going away in the next version of React.FC
, even now you can use React.VFC
propTypes
, displayName
etc, so they would need to be added explicitly if required.Upvotes: 31
Reputation: 366
In React, the return of a function is JSX.Element
. Even the return of the declaration in React.FC
must be JSX.Element
If you have implicit return:
const Component: React.FC = () => {}
If you have explicit return
const Component = (): JSX.Element => {}
Upvotes: 4
Reputation: 3703
React.FC
offers Type checking support
You can also write components with React.FunctionComponent (or the shorthand React.FC - they are the same):
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
Some differences from the "normal function" version:
Checkout docs for more information
https://github.com/typescript-cheatsheets/react/blob/main/README.md#section-2-getting-started
Upvotes: 7