Skip to content

Instantly share code, notes, and snippets.

@arnoldc
Last active February 10, 2024 14:05
Show Gist options
  • Save arnoldc/4b22f024c6c65b757d93297625807425 to your computer and use it in GitHub Desktop.
Save arnoldc/4b22f024c6c65b757d93297625807425 to your computer and use it in GitHub Desktop.
[React] React with Typescript (Tips/Tricks)
/*
* ──────────── Table of contents ────────────
*
* @1 - Get Props of element
* @2 - Get Props of component
* @3 - Strong typing of props
* @4 - Props for a generic component
* ──────────── Table of contents ────────────
*/
// @1 - Get Props of element
import * as React from 'react';
type InputProps = React.ComponentProps<"input">;
// @2 - Get Props of component
import * as React from 'react';
const SubmitButton = (props: { value: string }) => <input type="submit" {...props} />;
type SubmitButtonProps = React.ComponentProps<typeof SubmitButton>; // gets the ff => { value: string }
const MyComponent = (props: SubmitButtonProps) => {
// props.value
}
// @3 - Strong typing of props
// example 3.1
const Wrapper = (props: {
children?: ReactNode;
}) => {
return <div>{props.children}</div>;
};
// example 3.2 - Prop types can also be destructured,
const Wrapper = ({
children,
}: {
children?: ReactNode;
}) => {
return <div>{children}</div>;
};
// example 3.3 - Prop types can also be extracted to a type alias:
export type WrapperProps = {
children?: ReactNode;
};
const Wrapper = (props: WrapperProps) => {
return <div>{props.children}</div>;
}
// example 3.4 - Prop types can also be extracted to a type alias:
const Wrapper = ({ children }: WrapperProps) => {
return <div>{children}</div>;
};
// example 3.5 - Interfaces are another way to declare props:
export interface WrapperProps {
children?: ReactNode;
}
const Wrapper = (props: WrapperProps) => {
return <div>{props.children}</div>;
};
// example 3.6 - Interfaces are another way to declare props:
export interface InputProps extends ComponentProps<"input"> {
label: string;
}
// example 4 - Props for a generic component
interface Props<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
interface Slide {
title: string;
description: string;
}
function Carousel<T>({ items, renderItem }: Props<T>) {
// implementation here
}
const App: React.FC = () => {
retunr (
<Carousel<Slide>
items={[
{ title: 'title1', description: 'description1' },
{ title: 'title2', description: 'description2' },
]}
renderItem={(item) => (
// you can see in item that it has the following property now
<div>
<h2>{item.title}</h2>
<p>{item.description}</p>
</div>
)}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment