Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSX element class does not support attributes because it does not have a 'props' property [duplicate]

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'.
like image 688
Knight Yoshi Avatar asked Jun 25 '17 16:06

Knight Yoshi


People also ask

Why JSX element class does not support attributes?

jeffersoneagley changed the title JSX element class does not support attributes because it does not have a 'props' property.ts (2607) JSX element class does not support attributes because it does not have a 'props' property. ts (2607) on Nov 24, 2020. Copy link.

How to solve the error “JSX element type does not have any construct”?

The error "JSX element type does not have any construct or call signatures" occurs when we try to pass an element or react component as props to another component but type the prop incorrectly. To solve the error, use the React.ElementType type. Here is an example of how the error occurs.

Can you use class in JSX?

Attribute class = className The class attribute is a much used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX. Use attribute className instead. JSX solved this by using className instead.

What is JSX in react?

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React. JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement () and/or appendChild () methods.


2 Answers

The solution is to install the React Types defintions

yarn add -DE @types/react

More details from the typescript docs and from the types repo

On a side note I had to restart vscode for the linting to kick in properly.

like image 146
stilllife Avatar answered Oct 19 '22 23:10

stilllife


TypeScript follows the ES-module specification but React follows CommonJS. This article touches on that among other things.

Importing React like this will fix this problem:

import * as React from 'react';

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

    render () {
        return (<li>{this.props.children}</li>);
    }
}
like image 21
Jaap Avatar answered Oct 20 '22 01:10

Jaap