how to pass props in typescript code example
Example 1: 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 2: 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 3: state in react typescript
interface IProps {
}
interface IState {
playOrPause?: string;
}
class Player extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
playOrPause: 'Play'
};
}
render() {
return(
<div>
<button
ref={playPause => this.playPause = playPause}
title={this.state.playOrPause}
>
Play
</button>
</div>
);
}
}
Example 4: passing props using ts
playOrPause : 'Play'