xxxxxxxxxx
// Declare the type of the props
type CarProps = {
name: string;
brand: string;
price;
}
// usage 1
const Car: React.FC<CarProps> = (props) => {
const { name, brand, price } = props;
// some logic
}
// usage 2
const Car: React.FC<CarProps> = ({ name, brand, price }) => {
// some logic
}
xxxxxxxxxx
type Props = {
size: string;
}
const Component = ({ size = 'medium' }: Props) => (
<div className={cn('spinner', size)} />
);
xxxxxxxxxx
class Test extends Component<PropsType,StateType> {
constructor(props : PropsType){
super(props)
}
render(){
console.log(this.props)
return (
<p>this.props.whatever</p>
)
}
};
xxxxxxxxxx
// answer mainly copied from the answer of 'Clear Crab' https://www.codegrepper.com/profile/clear-crab-p3ip3vsw14e3
// but a little different
// * (different TypeScript, different child-comp render):
interface ParentCompProps {
childComp?: React.ComponentType; // <---
}
const ChildComp: React.FC = () => <h2>This is a child component</h2>
function ParentComp(props: ParentCompProps) {
const { childComp: ChildComp } = props; // <---
return (<div>{<ChildComp />}</div>); // <---
};
xxxxxxxxxx
import React from 'react'
type ImageProps = {
src: string
alt?: string
}
const FeatureImage: React.FC<ImageProps> = ({ src }) => {
return (
<div className="w-[300px] md:[300px] lg:[320px] shadow-2xl font-Raleway">
<img src={src} alt="Card Items 1" className="w-full h-auto" />
</div>
)
}
export default FeatureImage
xxxxxxxxxx
type ViewProps = React.ComponentProps<typeof View>
// or
type InputProps = React.ComponentProps<'input'>
xxxxxxxxxx
1 const ReactFCComponent: React.FC<{title:string}> = ({children, title}) => {
2 return <div title={title}>{children}</div>
3 }
xxxxxxxxxx
type GreetProps = typeof Greet.defaultProps & {
age: number;
};
class Greet extends React.Component<GreetProps> {
static defaultProps = {
age: 21,
};
/*...*/
}
// Type-checks! No type assertions needed!
let el = <Greet age={3} />;
xxxxxxxxxx
1interface OptionalMiddleName {
2 firstName: string;
3 middleName?: string;
4 lastName: string;
5}
6function Component({firstName, middleName = "N/A", lastName}:OptionalMiddleName){
7 // If middleName wasn't passed in, value will be "N/A"
8}
xxxxxxxxxx
export default function MyComponent(
{firstProp, secondProp}:{firstProp:number; secondProp:string;}
) {}