DEV Community

Discussion on: 6 ways to write a React component (TS Included)

Collapse
 
belinde profile image
Franco Traversaro • Edited

In typescript it's way more concise using the React.FC type:

const Button: React.FC = (props) => {
      return <button>{props.children}</button>
}
Enter fullscreen mode Exit fullscreen mode

It will check also the return type of the component, so if you're using some weird conditional return you'll be sure to return always a valid component.

It's a generic, so you can add the types of your props without caring of React's stuff:

type ButtonProps = {
   onClick: () => void
}
const Button: React.FC<ButtonProps> = ({children, onClick}) => (
   <button onclick={onClick}>{children}</button>
);
Enter fullscreen mode Exit fullscreen mode

Destructuring props is also a good way to KISS, and all the types are correctly inferred.

Collapse
 
lukemorales profile image
Luke Morales

There's a lot of discussion on the use of React.FC around the internet for various reasons, I don't think there's a right or wrong answer, but I rather not use React.FC as it breaks defaultProps and it accepts children being passed for every component (and that's not the behaviour you want for every component).

I rather type props the way the article presents or with the PropsWithChildren generic provided by React.

Just giving another insight to the discussion!

Collapse
 
mateo_garcia profile image
Mateo Garcia

Thank you both of you guys, as you said, we can use ReactFC or PropsWithChildren types. I forgot to annotate the component's output. However, I avoided props de-structuring on purpose just to make the functions more readable. Really cool feedback 🤓