Skip to content
loading...

re: React Typescript Cheatsheet VIEW POST

FULL DISCUSSION
 

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 }) => {};

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
 

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.

code of conduct - report abuse