Reputation: 3694
How to define React Class/Function components in TypeScript and have working typechecking? I not found any full article about how to do it properly.
I am able to define Props
and State
interface, but I dont know how to define defaultProps
, defaultState
, etc...
Can someone help me (and others) out with some good style? Thanks!
Upvotes: 0
Views: 97
Reputation: 1246
For a much simpler structure you could go from this:
import * as React from "react";
const App = ({ value = 'Hello World' }: { value: string }) => (
<div>
<h1>{value}</h1>
</div>
)
export default App
Where { value = 'Hello World' }
is your default props and { value: string }
is your typechecking
Here's cheatsheet guide that could help you with React + Typescript: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet
Upvotes: 1
Reputation: 1888
That's quite easy. You can still do it the old way. You can still declare it outside of your function
, like with this example App.defaultProps
:
import * as React from "react";
import "./styles.css";
export interface CatProps {
catName: string;
eyeColor: string;
age: string;
}
export default function App(props: CatProps) {
return (
<div>
{props.catName} Cat, Eye Color: {props.eyeColor}, Age: {props.age}
</div>
);
}
App.defaultProps = {
catName: "Sandy",
eyeColor: "deepblue",
age: "120"
};
Working sample: Try it
Mess around a little bit, and change the defaultProps
values.
Default State:
Using the example from above, you can define a defaultState
, simply doing:
const [catName, setCatName] = useState('Sandy'); // define a defaultState value inside useState hook
Upvotes: 0