TypeScript 'props' property does not exist

I have this .tsx file

import React, { Component } from 'react';

export class SidebarItem extends Component {
    constructor (props) {
        super(props);
    }

    render () {
        return (<li>{this.props.children}</li>);
    }
}

However, TypeScript throws this error: error TS2339: Property 'props' does not exist on type 'SidebarItem'.

+4
source share
3 answers

You can try the following way of writing React Comp.

interface SidebarItemProps
{
    children: any
} 

class SidebarItem extends React.Component<SidebarItemProps, any> { 
    //your class methods 
}

Learn more about using React in TypeScript.

+2
source

The solution is to install React type fixes

yarn add -DE @types/react

More from typescript docs and from repo types

On a side note, I had to restart vscode for the correct game.

+1
source

If your component has no state, you do not need to use the class at all. You can also use the stateless response component (SFC) as an answer to this question .

const MyStatelessComponent : React.StatelessComponent<{}> = props =>
    <li>{props.children}</li>;

Or if your markup gets huge:

const MyStatelessComponent : React.StatelessComponent<{}> = props => {

    return <li>{props.children}</li>;

}
0
source

Source: https://habr.com/ru/post/1680072/


All Articles