Skip to content

Instantly share code, notes, and snippets.

@tatchi
Last active February 2, 2019 06:55
Show Gist options
  • Select an option

  • Save tatchi/ecc98b0f70121f593ca03e2b60ce95e8 to your computer and use it in GitHub Desktop.

Select an option

Save tatchi/ecc98b0f70121f593ca03e2b60ce95e8 to your computer and use it in GitHub Desktop.
import React, { useReducer } from 'react';
import './styles.scss';
type Views = 'All' | 'Details';
type State = { view: Views };
export type AppActions =
| {
readonly type: 'ResetView';
}
| {
readonly type: 'SetView';
readonly payload: Views;
};
const initialState: State = { view: 'All' };
function reducer(state: State, action: AppActions): State {
switch (action.type) {
case 'ResetView':
return { ...state, view: 'All' };
case 'SetView':
return { ...state, view: action.payload };
default:
return state;
}
}
const Title: React.FunctionComponent<{ view: Views }> = ({ view }) => {
switch (view) {
case 'All':
return <>All Page</>;
case 'Details':
return <>Details Page</>;
default:
return <></>;
}
};
const NavButton: React.FunctionComponent<{
view: Views;
dispatch: React.Dispatch<AppActions>;
}> = ({ view, dispatch }) => {
switch (view) {
case 'All':
return (
<button
onClick={() => dispatch({ type: 'SetView', payload: 'Details' })}
>
Switch to Details Page
</button>
);
case 'Details':
return (
<button onClick={() => dispatch({ type: 'SetView', payload: 'All' })}>
Switch to All Page
</button>
);
default:
return null;
}
};
const App: React.FunctionComponent = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const { view } = state;
return (
<div>
<h1>
<Title view={view} />
</h1>
<div>
<NavButton view={view} dispatch={dispatch} />
</div>
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment