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 d
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.
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.