DEV Community

Discussion on: React Typescript Cheatsheet

Collapse
 
mixailnovikov profile image
Mikhail Novikov

Hello! Nice article, but I have some notes.

Children
To describe a 'children', I prefer to use React.FC generic type.

interface AnotherSpecificProps {}
const AnotherComponent: React.FC<AnotherSpecificProps> = ({ children }) => {};

// even with omitted props it's still working
const Component: React.FC = ({ children }) => {};

Enter fullscreen mode Exit fullscreen mode

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>>.

ComponentProps {
  prop: boolean;
  propAnother: string;
}
const Component: React.FC<ComponentProps> = ({prop, propAnother}) => {
  return (
    <div>
      {prop && propAnother}
    </div>
  );
};

interface ComplexComponentProps {
  componentProps?: Partial<React.ComponentProps<typeof Component>>
}
const ComplexComponent: React.FC<ComplexComponentProps> = ({componentProps}) => {
  return (
    <div>
      <Component prop={true} propAnother="string" {...componentProps} />
    </div>
  );
};

// somewhere else
<ComplexComponent />
<ComplexComponent componentProps={{prop: false}} />
// without Partial you should pass all required props, so Partial is very useful
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bendman profile image
Ben Duncan

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.