Here are a few patterns I find useful when building a project in React + Typescript. When starting out I didn't find the JSX and React types obvious or particularly well documented, so I'd like to maintain a list of what types to use in different situations.
This is just a start, so I'd love to know what patterns you all find useful and what I should add to the list. Also, if there is anything here that I shouldn't be doing I would love to know!
Table of Contents
Children
interface Props {
children?: React.ReactNode
}
Events
interface Props {
// Use the specific HTML element targeted
onClick?: (event: MouseEvent<HTMLButtonElement>) => void
}
Forwarding Props
To forward a named props object to an element:
interface Props {
buttonProps?: JSX.IntrinsicElements['button']
}
const Container = ({ buttonProps }: Props) => (
<div>
<button {...buttonProps}></button>
</div>
)
To forward top-level props to an element:
interface Props extends JSX.IntrinsicElements['button'] {}
const ExtendedButton = (props: Props) => (
<button {...props} />
)
Styles
// utils.d.ts
declare interface StyleProps {
style?: React.CSSProperties
className?: string
}
// Button.tsx
interface ButtonProps extends StyleProps {
label: string
}
const Button = ({ label, ...styleProps }: ButtonProps) => (
<button {...styleProps}>{label}</button>
)
Refs
Element refs:
const liRef = useRef<HTMLLIElement>(null)
Other refs are possible too:
const valueRef = useRef<number>(0)
Top comments (4)
Hello! Nice article, but I have some notes.
Children
To describe a 'children', I prefer to use
React.FC
generic type.Forwarding Props
Sometimes I need to pass additional props to the nested components, so there is a helpful generic
React.ComponentProps<typeof SomeComponent>
Also you can wrap it in
Partial<React.ComponentProps<typeof SomeComponent>>
.Thanks for these! The
React.ComponentProps<typeof Component>
looks especially useful for passing props down without needing to import the Props interface of the child component.Hey man, nice article!
I only see one problem. For me the " forward top-level props to an element" section doesn't work.
Because when I do:
I get this error:
However, there is an easy workaround to fix this problem:
But this seems really combersome and repetitive when you have to do this in every component.
I wrote a generator which basically generates me this:
I put this in a
global.d.ts
file so I don't even have to import it.Now I can use it like this:
Am I missing something? Is there a better solution to this? I think react should provide an easier type system for the end user in the first place tho... It was extremely frustrasting to find the right types when I started react.
This is awesome. Thanks. As I use TypeScript and React more I will definitely reach out and let you know if you need to add anything.