typescript react component as prop code example
Example 1: react tsx component example
import React from 'react';
interface Props {
}
const App: React.FC<Props> = (props) => {
return (
<div><div/>
);
};
export default App;
Example 2: react typescript props
type CarProps = {
name: string;
brand: string;
price;
}
const Car: React.FC<CarProps> = (props) => {
const { name, brand, price } = props;
}
const Car: React.FC<CarProps> = ({ name, brand, price }) => {
}
Example 3: react typescript pass component as prop
interface ParentCompProps {
childComp?: React.ReactNode;
}
const ChildComp: React.FC = () => <h2>This is a child component</h2>
const ParentComp: React.FC<ParentCompProps> = (props) => {
const { childComp } = props;
return <div>{childComp}</div>;
};
function App() {
return (
<>
<ParentComp childComp={<ChildComp />} />
<ParentComp childComp={<h3>Child component 2</h3>} />
<ParentComp childComp={(
<div style={{border: '2px solid red'}}>
<h4>Child component</h4>
<p>With multiple children</p>
</div>
)} />
</>
);
}
Example 4: TYPESCript props class component
class Test extends Component<PropsType,StateType> {
constructor(props : PropsType){
super(props)
}
render(){
console.log(this.props)
return (
<p>this.props.whatever</p>
)
}
};
Example 5: ts react props type
type Props = {
size: string;
}
const Component = ({ size = 'medium' }: Props) => (
<div className={cn('spinner', size)} />
);
Example 6: get typescript props of component
type ViewProps = React.ComponentProps<typeof View>
type InputProps = React.ComponentProps<'input'>