Now that we have a common base whether you use the create-react-app locally or CodeSandbox, we can start building our app.

Given the premise of the introduction, we’ll start with 3 components: AddProduct, ProductsList and SingleProduct, which will provide

  • the add product form
  • the products list
  • the single product view

Those components will all be added to the navigation on top of the page, along with “Home” and “About”.

Let’s start by adding them, with a minimal boilerplate to just see them working as part of the router:

Create src/components folder and add

src/components/AddProduct.js

import React from 'react'

export default () => {
  return <div>AddProduct</div>
}

src/components/SingleProduct.js

import React from 'react'

export default () => {
  return <div>SingleProduct</div>
}

src/components/ProductsList.js

import React from 'react'

export default () => {
  return <div>ProductsList</div>
}

Next, open App.js.

First we need to import React router:

import { BrowserRouter as Router, Link, Route } from 'react-router-dom'

Then we import the components we just created:

import AddProduct from './components/AddProduct.js'
import ProductsList from './components/ProductsList.js'
import SingleProduct from './components/SingleProduct.js'

Now we can use this React Router basic structure:

const App = () => {
  return (
    <Router>
      <div>
        <aside>
          <Link to={`/`}>Products</Link>
          <Link to={`/add-product`}>Add product</Link>
        </aside>

        <main>
          <Route exact path="/" component={ProductsList} />
          <Route
            path="/add-product"
            component={AddProduct}
          />
          <Route path="/product/:slug" component={SingleProduct} />
        </main>
      </div>
    </Router>
  )
}

Notice how we add a specific path to each component, and the Product component accepts a dynamic path /product/:slug. There will be multiple pages on the site that match the Product component, one for each different product.

Now replace the src/App.css content with this:

input,
textarea {
  border: 1px solid #ccc;
  padding: 20px;
  vertical-align: middle;
}

label {
  vertical-align: middle;
  padding-right: 10px;
}

div {
  display: block;
  padding: 50px;
  font-size: 1.5rem;
}

.button {
  background-color: #2c3e50;
  color: white;
  font-size: 1.5rem;
  width: 50%;
}

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
aside {
  padding: 30px;
}

aside a {
  font-weight: bold;
  color: #2c3e50;
  padding: 20px;
}

aside a.router-link-exact-active {
  color: #42b983;
}

You don’t need to understand it if you are not a CSS expert, but it should just give the app a better look.

The final result should be this:

And you should be able to see the AddProduct screen when you click the link.


Go to the next lesson