Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Last active February 18, 2024 23:48
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joshwcomeau/2a31d790fbd80edae0a562e96d503a46 to your computer and use it in GitHub Desktop.
Save joshwcomeau/2a31d790fbd80edae0a562e96d503a46 to your computer and use it in GitHub Desktop.
Naive Router
// Hello there!
//
// This is an example of the simplest, most naive router I could come up with.
//
// When it comes time for you to build a full-fledged, production-ready app,
// you're better off using an established standard like React Router.
//
// There is tremendous educational value in working this stuff out yourself,
// though! I believe that even those very new to React could work out a
// basic router like this.
//
// There are, of course, many possible improvements. I'd encourage those learning
// React to play with this concept and see how close to a "proper" router you can
// get!
import React, { Component } from 'react';
import './App.css';
// Routes
const Home = () => <div>Home</div>;
const About = () => <div>About</div>;
const Contact = () => <div>Contact</div>;
const NotFound = () => <div>Not Found</div>;
class App extends Component {
renderRoute() {
switch (window.location.pathname) {
case '/': return <Home />;
case '/about': return <About />;
case '/contact': return <Contact />;
default: return <NotFound />;
}
}
render() {
return (
<div>
{this.renderRoute()}
</div>
);
}}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment