Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactj, typescript Property 'setState' is missing in type

I'm getting a ts error from my react component. The component is running fine, building etc, however typescript is showing an error inside the ide. Not sure how i need to declare this to remove the error. I've tried to create a setState method inside the component itself, but this was giving even more errors.

Error:(15, 19) TS2605:JSX element type 'Home' is not a constructor function for JSX elements. Property 'setState' is missing in type 'Home'.

"typescript": "^2.3.4",

"react": "^15.5.4",

"react-dom": "^15.5.4",

!----

export class App extends React.Component<Props, State> {
  public state: State
  public props: Props

 constructor(props: Props) {
  super(props)
  this.state = {
    view: <Home />, <<<<
    } 

-- the rest removed for brevity

export class Home extends React.Component<Props, State> {
public state: State;
public props: Props;

constructor(props: Props) {
    super(props)

}
  public render() {
    return <h1>home</h1>
  }
}
like image 514
Jimi Avatar asked Jun 15 '17 13:06

Jimi


2 Answers

Had the same issue, but my problem was that I was importing React wrong.

The correct way to import it when using TypeScript is with import * as React from "react".

Code example:

import * as React from "react"
import ReactDOM from "react-dom"

class App extends React.Component<any, any> {
  render() {
    return (
      <div>Hello, World!</div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("app"))

Note: <any, any> allows you to use any props and state variables in your React component, but you should usually define those yourself to take advantage of TypeScript's type annotations.

like image 57
Telmo Trooper Avatar answered Oct 15 '22 02:10

Telmo Trooper


Here's an example of how to use the state and render the components:

type HomeProps = {
    text: string;
}
class Home extends React.Component<HomeProps, void> {
    public render() {
        return <h1>{ this.props.text }</h1>
    }
}

type AppState = {
    homeText: string;
}
class App extends React.Component<void, AppState> {
    constructor() {
        super();

        this.state = {
            homeText: "home"
        };

        setTimeout(() => {
            this.setState({ homeText: "home after change "});
        }, 1000);
    }

    render() {
        return <Home text={ this.state.homeText } />
    }
}

As you can see, the props and state objects are always simple, and the rendering method is in charge of creating the actual components.
This way react knows which components are changed and which parts of the DOM tree should be updated.

like image 44
Nitzan Tomer Avatar answered Oct 15 '22 03:10

Nitzan Tomer