ReasonJun

React.FC and JSX.Element 본문

Frontend/React

React.FC and JSX.Element

ReasonJun 2023. 7. 12. 16:13
728x90

React.FC and JSX.Element are both types that are used in TypeScript to represent React components. However, there are some key differences between the two types.

  • React.FC is a type that is specifically designed for React components. It has an implicit children prop, which means that the component will accept children even if the children prop is not explicitly defined. React.FC also has default support for other/static properties like propTypes, displayName etc, so they would need to be added explicitly if required.
  • JSX.Element is a more general type that can be used to represent any kind of value that can be rendered by React. This includes React components, strings, numbers, and objects. JSX.Element does not have an implicit children prop, so the children prop must be explicitly defined.

In general, you should use React.FC when you are writing a React component. This will give you the most type safety and make your code easier to understand. However, you can also use JSX.Element if you need to represent a React component in a more general way.

 

// React.FC example
const MyComponent = React.FC<{ name: string }>({
  render() {
    return <div>Hello, {this.props.name}</div>;
  },
});

// JSX.Element example
const MyComponent = () => <div>Hello, world</div>;

In the first example, MyComponent is a React.FC component. This means that it has an implicit children prop, so it can accept children even if the children prop is not explicitly defined. The render() function of MyComponent takes a name prop as input and returns a div element with the name of the person being greeted.

 

In the second example, MyComponent is a JSX.Element. This means that it does not have an implicit children prop, so the children prop must be explicitly defined. The MyComponent function returns a div element with the text "Hello, world".

 

Here is a table that summarizes the differences between React.FC and JSX.Element:

 

Property React.FC JSX.Element
Type specific general
Children prop implicit explicit
Default support for other/static properties yes no
Usage React components general

 

https://medium.com/@RobertoSilvaZ/when-should-i-use-jsx-element-or-react-fc-29e61eb1e754

 

When should I use JSX.Element or React.FC?

It is a good practice to use the appropriate type for your JSX elements and function components

medium.com

 

728x90

'Frontend > React' 카테고리의 다른 글

React18 : How React 18 Improves Application Performance in Detail  (0) 2023.09.09
React : context (state management)  (0) 2023.08.11
JSX.Element vs ReactNode vs ReactElement  (0) 2023.07.12
React 18 : Transition  (0) 2023.06.16
React 18 : Suspense  (0) 2023.06.16
Comments