Create a Single Page Application with React and React Router

  • Create Your React App

We will use create-react-app to create a travel blog website and use React Router. 

npx create-react-app react-router-blog-example

cd react-router-blog-example

npm start

You should automatically be routed to localhost:3000 unless you have something else running on that port. You should see the default React app template:

  • Create Your Paths and Routes with React Router

Now, let’s set up our App.js file. First, we are going to create a list of links: Home, About, and Users. 

<ul>

<li>

<Link to=”/”>Home</Link>

</li>

<li>

<Link to=”/about”>About</Link>

</li>

<li>

<Link to=”/cuisine”>Cuisine</Link>

</li>

</ul>

Next, we need to add a separate <Route> for each page. Think of this as different URLs for each link. Although we are making a single page application, we will still have different links for different parts of the app. Let’s add a path that will correspond to each of our links and wrap them all in a <Switch>. A <Switch> looks through its children’s Routes and renders the first one that matches the current URL.

<Switch>

<Route path=”/about”>

<About />

</Route>

<Route path=”/cuisine”>

<Cuisine />

</Route>

<Route path=”/”>

<Home />

</Route>

</Switch>

  • Insert Your Components

Notice in each path, we have the corresponding component. Then, we need to add content to our components. In this example, but feel free to use any component library you like. We are going to create three different cards for each of the links: HomeCard, AboutCard, and CuisineCard, which will each be the main component of the different pages. First, I import the component from rebass, choose an image to be in the card, and then add it to my App.js file

class HomeCard extends React.Component {
 render() {
   return (
     <Box width={500}>
       <Card
         sx={{
           p: 1,
           borderRadius: 2,
           boxShadow: '0 0 16px rgba(0, 0, 0, .25)',
         }}
       >
         <Image src={image} />
         <Box px={2}>
           <Heading as="h3">Talia's Travels</Heading>
           <Text fontSize={0}>Bon Voyage!</Text>
         </Box>
       </Card>
     </Box>
   );
 }
}

Leave a comment

Your email address will not be published. Required fields are marked *