Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS TS, Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly<MyProps>'

I am trying to type the props of my component and use an URL param at the same time. I get the following error:

Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly'

Here is some of my code:

import Api from '../../api/Api';

interface MyProps {
    api: Api
}

interface MyState {
    someString: string,
    loading: boolean
}

export class MyComponent extends React.Component<MyProps, MyState> {

    constructor(props: MyProps) {
        super(props);
        this.state = {
            someString: this.props.match.params.someString,//<-- Error is here on this line
            loading: true
        }
    }

    componentDidMount() {
        this.props.api.getSomeInfo(this.state.someString, this.callback)
    }

    callback() {
        let interval = setInterval(function () {
            this.setState({loading: false});
            clearInterval(interval)
        }, 3000);
    }

    render() {
        return (
            <div>
                <p>{this.someString}</p>
            </div>
        );
    }
}

As you can see all I am trying to do is:

1- Go to:

http://localhost:8080/someStrings/:someString

2- Grab the value of :someString in my component's constructor and store in state

3- Use the value of someString in my state to be able to pass it as an argument to my API module to do stuff

4- When the callback is executed in the API I remove the loading animation

My question is basically, how do I declare my MyProps to be able to acheive this?

like image 970
Sebastien Avatar asked May 01 '18 13:05

Sebastien


2 Answers

This is an open issue in type definition. https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17355

Workaround

import { RouteProps } from 'react-router';
import React from 'react';

interface MyProps {
    api: Api
}

interface MyState {
    someString: string,
    loading: boolean
}

class MyComponent extends React.Component<Props & RouteProps, State> // Pay attention here.
{
  // your code...
}

ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17355#issuecomment-336022780

like image 180
Ritwick Dey Avatar answered Sep 27 '22 20:09

Ritwick Dey


This is how I solved it

import {RouteComponentProps} from 'react-router';
interface IMyProps {}

interface IReactRouterParams {
  roomName: string;
  username: string;
}
export class MyComponent extends React.Component<
  IMyProps & RouteComponentProps<IReactRouterParams> {
 
  constructor(props: any) {
    super(props);
    //everything works here
    const {roomName, username} = this.props.match.params;
  }
}
like image 43
makkusu Avatar answered Sep 27 '22 18:09

makkusu