React Component Setup
1. Set up types file for react component props and state
src/types/Redux.d.ts
import { Dispatch } from 'react-redux';
import { User } from './User.d';
import { register_fntype } from '../actions/userActions';
export interface Action {
type: string;
}
export interface UserAction extends Action {
data?: User;
error?: string;
}
export type Users = Array<User>;
export type UserState = User | {};
// defines types of everything in Redux Store
export interface Store {
user: User;
}
// defines Prop types passed to the Register React component
// this would define any redux actions and state passed into the component
// essentially, anything in mapStateToProps and mapDispatchToProps would be
// defined here
export interface RegisterProps {
register: register_fntype;
completeRegistration: any;
}
src/types/Register.d.ts
// defines the types of everything stored in the react component state
export interface RegisterState {
firstName: string;
lastName: string;
email: string;
password: string;
username: string;
shouldRedirect: boolean;
}
2. Set Up React Component
src/RegisterLoginPage/Register.tsx
import * as React from 'react';
import { connect } from 'react-redux';
import { Store } from '../types/Redux';
import { RegisterState } from '../types/Register.d';
import { RegisterProps } from '../types/Redux.d';
import { register } from '../actions/userActions';
import { showRegisterWindow, completeRegistration} from '../actions/appActions';
class Register extends React.Component<RegisterProps, RegisterState> {
constructor(props: RegisterProps) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
password: '',
username: '',
shouldRedirect: false
};
}
public handleSubmit(e: React.FormEvent<HTMLButtonElement>): void {
e.preventDefault();
const { firstName, lastName, username, email, password } = this.state;
// this is where the register redux action is called and
// appropriate parameters passed in.
this.props.register(firstName, lastName, username, email, password)
// once register is done, calls the completeRegistration action
.then(() => { this.props.completeRegistration(); });
}
render() {
return (
<div>
{ the rest of the form }
<button onClick={e => this.handleSubmit(e)}>
Sign Up
</button>
</div>
);
}
}
// this is where you request keys from the Redux Store.
function mapStateToProps(state: Store) {
return {
visibleRegisterWindow: state.registerLoginWindow.visibleRegisterWindow
};
}
// connect function maps the Redux store and actions to the Register component
export default connect(
mapStateToProps,
{ register, completeRegistration } // shorthand for mapDispatchToProps
)(Register as any);
Last updated