loading...
Cover image for 
How to Do Routing Using Only React State

How to Do Routing Using Only React State

julianeon profile image Julian Martinez ・4 min read

So you have a site you just created in React, probably using create-react-app. In my last tutorial, I did this, and added some basic styling.

It's decent, but not great.

Now you want things to appear on their own page: each blog post should get its own, and there should also be an About page, and maybe a Corporate Values or a Team page.

For this, there are multiple solutions. You can do this using React Router, covered in many tutorials already - but did you know you can also use state?

Here's how it looks, when complete.

http://reactstate.s3-website-us-east-1.amazonaws.com/

Here's how to create it.

The Whole Lesson, In One Screenshot

I used useState for months before realizing it could be used with a function; and by doing that, you can also use it do routing.

Also I love explanations like this that can be entirely self-contained in one screenshot-sized text block, as shown below.

import React, { useState } from 'react';

export default function App() {
  const [Page, setPage] = useState(() => Home);

  const navigateTo = component => setPage(() => component);

    return (
        <div>
          <Page />                  
          <div>
            <button onClick={() => navigateTo(Home)}>Home</button>
            <button onClick={() => navigateTo(Email)}>Email</button>
            <button onClick={() => navigateTo(Calendar)}>Calendar</button>
          </div>
        </div>
  )
}

function Home() { return ( <div>Home page</div> ) }
function Email() { return ( <div>Email page</div> ) }
function Calendar() { return ( <div>Calendar page</div> ) }

To be fair, this doesn't have some major advantages of React Router, like a forward and a back button, or a history. But it simplifies a routing tutorial by a lot, and there's no boilerplate; it doesn't get much simpler than this.

Now you could stop here if that explains it for you, but if you'd like to see how I implemented this into my one page sample site, read on.

Basic Structure

Let's say you did create-react-app, to create our app's directory structure.

You run this command:

npx create-react-app blog

Then you edit the default App.js page to have a title and show some text.

My example site is about tech companies; each paragraph-sized post will has a description of a famous one - Amazon, Google, Apple, FaceBook. All the code I've personally written is in a single file, in App.js.

There's just five components: one for each company, and one more to space them so they're not quite flush with the left side of the page. They are Google, Amazon, Facebook, Apple, and Spacer.

This last one, Spacer, is a styled component, meaning you now have a dependency, styled-components; you can add it with the command 'yarn add styled-components', from your root directory.

Here's how the code looks, condensed to only the essentials.

import React from 'react';

const Google = () => (
  <p>This is Google. It's a search engine started by Sergey Brin and Larry Page.</p>
  <p>PageRank is the search algorithm that started it all. Today's it's a 100 trillion dollar company.</p>
)

//then a bunch of other components like the Google one, just with different text...

function App(){
  return (
    <Spacer>
    <Google/>
    <Amazon/>
    <FaceBook/>
    <Apple/>
    </Spacer>
  );
}

export default App;

Here's what it looks like; as you can see, it's really basic.

minimum

Adding Routing

Now I take the routing material shown it in the screenshot, and integrate it into my file.

Here's how it looks, when complete.

norouter

You can see the routing in action through the row of buttons, on the bottom. Press one, and you're routed to where you need to go.

Click on the link to see the live website!

http://reactstate.s3-website-us-east-1.amazonaws.com/

Here's the code, taken from the same above and implemented in my file.

const NavButtons = ({setter}) => (
      <Spacer>
        <button onClick={()=>setter(()=>Home)}>Home</button>
        <button onClick={()=>setter(()=>Amazon)}>Amazon</button>      
        <button onClick={()=>setter(()=>Google)}>Google</button>
        <button onClick={()=>setter(()=>Apple)}>Apple</button>
        <button onClick={()=>setter(()=>FaceBook)}>FaceBook</button>
        <button onClick={()=>setter(()=>About)}>About</button>
      </Spacer>
)

export default function App() {
  const [Page, setPage] = useState(() => Home);
    return (
        <OneColumn>
          <Spacer>
            <Page />
            <NavButtons setter={setPage}/>
          </Spacer>
        </OneColumn>
    )
}

Basically I use state to set how the page should look. In order to help with this, I pass the state-setter, setPage, to the NavButtons component. I could've also used useContext, but I chose this method for its simplicity.

You can see the GitHub repo below and the App.js file that has all the code I've written.

https://github.com/julianeon/react-state-router

I also have two other App.js file versions in the repo, for relatively simpler and more advanced version of the same lesson.

I hope this helps, and thanks for reading!

You can also read this tutorial on the reactever website.

My name is Julian Martinez and I'm a consultant for web and cryptocurrency projects. If you'd like to discuss a project, see my About section & contact form.

For more content like this, follow me on Twitter.

Posted on by:

julianeon profile

Julian Martinez

@julianeon

I'm interested in development as it relates to JavaScript, React, AWS, Go, and cryptocurrencies. Also I'm friendly.

Discussion

markdown guide
 

This is an interesting idea, though, I am not sure if it can be called routing. Nonetheless, thank you for writing it.