TYPESCript props class component code example

Example 1: typescript react class component

import * as React from 'react';

export interface TestProps {
    count: number;
}
 
export interface TestState {
    count: number;
}
 
class Test extends React.Component {
    state = { count:0  }
    render() { 
        return ( 

this is test

); } } export default Test;

Example 2: react typescript props

// Declare the type of the props
type CarProps = {
  name: string;
  brand: string;
  price;
}

// usage 1
const Car: React.FC = (props) => {
  const { name, brand, price } = props;
  // some logic
}

// usage 2
const Car: React.FC = ({ name, brand, price }) => {
	// some logic
}

Example 3: TYPESCript props class component

class Test extends Component {
  constructor(props : PropsType){
    	super(props)
  }
  
  render(){
   	console.log(this.props) 
    return (
     	

this.props.whatever

) } };

Example 4: state in react typescript

interface IProps {
}

interface IState {
  playOrPause?: string;
}

class Player extends React.Component {
  // ------------------------------------------^
  constructor(props: IProps) {
    super(props);

    this.state = {
      playOrPause: 'Play'
    };
  }

  render() {
    return(
      
); } }

Example 5: ts react props type

type Props = {
  size: string;
}

const Component = ({ size = 'medium' }: Props) => (
  
);

Tags:

Misc Example