score:93
thanks all for the answers. they are correct but i was looking for a more detailed version. i did some more research and found this on react+typescript cheatsheets on github.
function components
these can be written as normal functions that take a props argument and return a jsx element.
type appprops = { message: string }; /* could also use interface */
const app = ({ message }: appprops) => <div>{message}</div>;
what about react.fc
/react.functioncomponent
?
you can also write components with react.functioncomponent
(or the shorthand react.fc
):
const app: react.fc<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
some differences from the "normal function" version:
it provides typechecking and autocomplete for static properties like displayname
, proptypes
, and defaultprops
- however, there are currently known issues using defaultprops
with react.functioncomponent
. see this issue for details - scroll down to our defaultprops
section for typing recommendations there.
it provides an implicit definition of children (see below) - however there are some issues with the implicit children type (e.g. definitelytyped#33006), and it might be considered a better style to be explicit about components that consume children, anyway.
const title: react.functioncomponent<{ title: string }> = ({
children,
title
}) => <div title={title}>{children}</div>;
in the future, it may automatically mark props as readonly, though that's a moot point if the props object is destructured in the parameter list.
react.functioncomponent
is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).
in most cases, it makes very little difference which syntax is used, but the
react.fc
syntax is slightly more verbose without providing clear advantage, so precedence was given to the "normal function" syntax.
score:11
since you are using react and typescript, you should always use the first pattern, as it will ensure that your component is more strictly typed since it implies that the printname
will be of type react functional component, and it takes in props of type props
.
const printname: react.fc<props>
you may read the full interface definition for functional components on the react typescript typings repository.
the second example you have provided does not provide any form of typings, except that it is a function that takes a set of parameters of type props
, and that it can return anything in general.
therefore, writing
const printname2 = (props:props)
is akin to
const printname2: jsx.element = (props:props)
as typescript is definitely unable to automatically infer that it is a functional component.
score:17
best solution:
the second approach + a return type
const printname2 = ({ prop1, prop2 }: props): jsx.element => { /** */}
this gives you complete control over the props and is more explicit (there is no hidden magic).
link to github pr to remove react.fc
kent c dodds has some thoughts why this is here
sub-optimal solution:
the first version (react.fc) will add a few types for you - they come from the react typings
interface functioncomponent<p = {}> {
(props: propswithchildren<p>, context?: any): reactelement | null;
proptypes?: weakvalidationmap<p>;
contexttypes?: validationmap<any>;
defaultprops?: partial<p>;
displayname?: string;
}
this approach is useful for a few reasons but an obvious one is if your component has children, then you don't need to manually add a children
prop. it's not great because there are issues with default props and many components don't have children.
score:65
react.fc
is not the preferable way to type a react component, here's a link.
i personally use this type:
const component1 = ({ prop1, prop2 }): jsx.element => { /*...*/ }
short list of react.fc
cons:
- provides an implicit definition of children, even if your component doesn't need to have children. that might cause an error.
- doesn't support generics.
- doesn't work correctly with
defaultprops
.
Source: stackoverflow.com
Related Query
- TypeScript and React - children type?
- How to use refs in React with Typescript
- Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type
- PropTypes in a TypeScript React Application
- Set types on useState React Hook with TypeScript
- Default property value in React component using TypeScript
- Importing images in TypeScript React - "Cannot find module"
- TypeScript React.FC<Props> confusion
- How to specify (optional) default props with TypeScript for stateless, functional React components?
- Extending HTML elements in React and TypeScript while preserving props
- How to define css variables in style attribute in React and typescript
- Typescript - "Cannot find name" errors in React components
- Cannot find namespace 'ctx' error when creating Context with react - typescript
- How do I restrict the type of React Children in TypeScript, using the newly added support in TypeScript 2.3?
- Using state in react with TypeScript
- TypeScript workaround for rest props in React
- What is the TypeScript return type of a React stateless component?
- React - using TypeScript vs Flow vs?
- React 18 TypeScript children FC
- React Router - Typescript errors on withRouter after updating version
- Typescript types for React checkbox events and handlers?
- allow typescript compiler to call setState on only one react state property
- VSCode prettier adds `value` to imports in TypeScript React
- React + TypeScript usage of className prop
- React TypeScript 16.8 How to make useEffect() async
- React with Typescript -- Generics while using React.forwardRef
- interface states and props in typescript react
- React with Typescript - Type { } is missing the following properties from type
- React component type in TypeScript
- react typescript testing TypeError: MutationObserver is not a constructor
More Query from same tag
- React: CMD File to Run Application
- Best way to split strings?
- Why can't i import my component from the same folder?
- React rendering based on boolean in state: ternary not working
- Why does React.StrictMode break calculating a diff of props/state?
- Redux presentation component UI state management
- How do I reset the react flux store to its initial state?
- Wrap TextArea default value
- Deconstruct and convert in React
- How to update a value in array Reactjs
- How to make Auto Slides Per View with dynamic content using Swiper Reactjs
- Updating state from an array with react useState hook
- React Hooks - How to useState or useEffect without affecting subscription?
- React force transition to end on hover
- Undefined is not an object evaluating this.state.*
- props in functional component
- Add react component in single spa microfrond end root-config
- How to render multiple components with different component name?
- Dispatch is not a function useContext/useReducer React hooks
- browserHistory undefined (react router v3)
- Unable to send formData to nodejs server
- Push object in array when checkbox is checked and remove object when checkbox is unchecked in ReactJS
- Rendering array of object object data in array.map() in react
- How to allow modal to close itself in React?
- React.memo reset state to previous
- Central style sheet for react native?
- react project variable is not defined error
- WebSockets with functional components
- React JS Custom Sidebar Navigation
- Storybook with absolute paths