I'm trying to figure out how to reduce the amount of boilerplate when using React, Redux and TypeScript together. It might be that you can't in this case, but wanted to see if anyone has ideas.
I currently have a component that dispatches an action that toggles a menu, alternating between showing and hiding it. To do this I've defined my class something like this (omitting code related to state, focusing on the dispatching of action):
import {Action, toggleMenu} from "../../actions/index";
interface IConnectedDispatch {
toggleMenu: (isActive: boolean) => Action;
}
class HeaderMenu extends React.Component<IOwnProps & IConnectedState & IConnectedDispatch, any> {
constructor(props: IOwnProps & IConnectedState & IConnectedDispatch) {
super(props);
this.toggleMenuState = this.toggleMenuState.bind(this);
}
public render() {
return (
<button className={buttonClass} onClick={this.props.toggleMenu(this.props.isActive)} type="button">
</button>
);
}
}
const mapDispatchToProps = (dispatch: redux.Dispatch<Store.All>): IConnectedDispatch => ({
toggleMenu: (isActive: boolean) => dispatch(toggleMenu(isActive))});
The action is defined as
export function toggleMenu(isActive: boolean): Dispatch<Action> {
return (dispatch: Dispatch<Action>) => {
dispatch({
isActive,
type: "TOGGLE_MENU",
});
};
}
It feels like it should be possible to reduce the amount of code required to accomplish my goal here. Being new to React, Redux and TypeScript I fail to see exactly how though. Specifically it feels very repetitive to write the action name, toggleMenu, over and over. For example twice in this part:
const mapDispatchToProps = (dispatch: redux.Dispatch<Store.All>): IConnectedDispatch => ({
toggleMenu: (isActive: boolean) => dispatch(toggleMenu(isActive))});
Any advice is appreciated!