Agenda:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
you can run TypeScript with --allowSyntheticDefaultImports (or add "allowSyntheticDefaultImports": true to tsconfig) to import like in regular jsx:
import React from 'react';
import ReactDOM from 'react-dom';
you can also modify TSLint file:
{
-"extends": ["tslint:recommended", "tslint-react", "tslint-config- prettier"],
+"extends": [],
+"defaultSeverity": "warning"
}
Stateless Functional Component:
const App = ({ message }: { message: string }) => <div>{message}</div>;
const App: React.SFC<{ message: string }> = ({ message }) => <div>{message}</div>;
SFC type that is the alias of StatelessComponent interface.
class App extends React.Component<{
message: string, // it takes one prop called 'message' which is a string type
}> {
render() {
return (
<div>{this.props.message}</div>
);
}
}
Within TypeScript, React.Component is a generic type (aka React.Component<PropType, StateType>), so you actually want to provide it with prop and (optionally) state types:
class App extends React.Component<{
message: string, // this is the prop type
}, {
count: number, // this is the state type
}> {
state = {
count: 0
}
render() {
return (
<div>{this.props.message} {this.state.count}</div>
);
}
}
export declare interface AppProps {
children1: JSX.Element; // bad
children2: JSX.Element | JSX.Element[]; // meh
children3: React.ReactChild | React.ReactChildren; // better
children: React.ReactNode; // best
style?: React.CSSProperties; // for style
onChange?: (e: React.FormEvent<HTMLInputElement>) => void; // form events!
props: Props & React.HTMLProps<HTMLButtonElement> // to impersonate all the props of a HTML element
}
onChange = (e: React.FormEvent<HTMLInputElement>): void => {
this.setState({text: e.currentTarget.value})
}