Skip to content

Instantly share code, notes, and snippets.

@justinbiebur
Created August 6, 2020 07:22
Show Gist options
  • Save justinbiebur/23537cc1b9fa246677bc649bfa5acc6e to your computer and use it in GitHub Desktop.
Save justinbiebur/23537cc1b9fa246677bc649bfa5acc6e to your computer and use it in GitHub Desktop.
Routing without React-Router
export const NavigationContext = React.createContext()
export default class NavigationProvider extends React.Component {
constructor(props) {
super(props)
this.state = {
pathname: window.location.pathname,
navigate: this.navigate,
}
window.onpopstate = () => {
this.setState({ pathname: window.location.pathname })
}
}
render() {
return (
<NavigationContext.Provider value={this.state}>
{this.props.children}
</NavigationContext.Provider>
)
}
navigate = (pathname) => {
this.setState({ pathname })
window.history.pushState(null, null, pathname)
}
}
const Route = ({ children, href }) => {
var navObj = useContext(NavigationContext);
var copy={...navObj};
switch(copy.pathname){
case href :
return(children);
default:
return null;
}
}
export default Route;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment