Search code examples
javascriptreactjstypescripttsx

How to implement e and props in React TypeScript?


I have a JS Component in which I have defined some normal jsx functions and states and now I want to use them as props in a tsx file, but since I'm a beginner, I'm confused. this is the js version of what I want to implement in tsx:

export class FormUserDetails extends Component {
  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  render() {
    const { values, handleChange } = this.props;
    return (
    ...
            <AppBar title="Enter User Details" />
            <TextField
              placeholder="Enter Your First Name"
              label="First Name"
              onChange={handleChange('firstName')}
              defaultValue={values.firstName}
              margin="normal"
                            fullWidth="true"
            />
...

How to implement this in React TypeScript with:

export class MainInfo extends Component<Props,{}>

or similar?

Sandbox:it has my tsx file that I want to implement like my example in question and the JS file defining my props https://codesandbox.io/s/tsx-rj694


Solution

  • hi you can make types for your class component this way

    interface IProps {
     nextStep: () => void;
     values: {
        firstName: string
     };
     handleChange: (value: string) => void
    }
    
    export class FormUserDetails extends Component<IProps> {
      continue = e => {
        e.preventDefault();
        this.props.nextStep();
      };
    
      render() {
        const { values, handleChange } = this.props;
        return (
        ...
                <AppBar title="Enter User Details" />
                <TextField
                  placeholder="Enter Your First Name"
                  label="First Name"
                  onChange={handleChange('firstName')}
                  defaultValue={values.firstName}
                  margin="normal"
                                fullWidth="true"
                />
    ...