Skip to content

Instantly share code, notes, and snippets.

@mngyuan
Created June 20, 2020 01:35
Show Gist options
  • Save mngyuan/af6d595d3fb166f9faaa88d275144835 to your computer and use it in GitHub Desktop.
Save mngyuan/af6d595d3fb166f9faaa88d275144835 to your computer and use it in GitHub Desktop.
Vanilla react site with redux style router
import React from 'react';
const Home = ({dispatch, currentRoute}) => {
<span>
You're at Home {currentRoute}.
<a onClick={() => dispatch({type: 'PUSH', path: '/about'})}>
About
</a>
</span>
};
const About = ({dispatch, currentRoute}) => {
<span>
You're at About {currentRoute}.
<a onClick={() => dispatch({type: 'PUSH', path: '/'})}>
About
</a>
</span>
};
const router = (state = { routes: ['/'] }, action) => {
switch (action.type) {
case 'PUSH':
window.location = action.path;
return { routes: state.routes.push(action.path) };
case 'POP':
window.location = state.routes[state.routes.length - 1];
return { routes: state.routes.slice(0, state.routes.length - 2) };
default:
return state;
}
}
const Router = () => {
const [routeState, setRouteState] = useState(router());
const dispatch = (action) => setRouterState(router(routeState, action));
const currentRoute = routeState.routes[routeState.routes.length - 1];
return currentRoute === '/' ? (
<Home
currentRoute={currentRoute}
dispatch={dispatch}
/>
) : (
<About
currentRoute={currentRoute}
dispatch={dispatch}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment