Adding the product details page

We're now in a position where we can code in the mechanism to handle the click through to a Product Details page.

Learning Objectives

Setting up routing

Step 1

The first step is to create a component that React can render when a user clicks on a 'Full details' link. We'll call it ProductDetails. Here's the code to add inside ProductDetails.js:

function ProductDetails (props) {
    const {
        name,
        description,
        images: [
            {
                title,
                imageSrc
            }
        ],
        price,
        addedToCart
    } = product
    return (
        <div class="product-details">
            <div class="product-details__main">
                <img src={imageSrc} alt={title} />
            </div>
            <aside>
            <h3>{name}</h3>
            <p>
                {description}
            </p>
            <p>
                &pound;{price}
            </p>
            <button onClick={() => props.addToCart(props.product)}>{addedToCart ? 'Remove from' : 'Add to'} cart</button>
            </aside>
      </div>
    )
}

export default ProductDetails

NB I'm using a different style of exporting here. When I import this I don't need to use the curly braces. It's not good to mix styles in your code. I just want you to know about the different ways you can export and import functions in ES6 javascript.

Import your component and create the route in App. Slot the following snippets into the right places in your App.js file.

import ProductDetails from './ProductDetails'

/* previously written code */

<Route path="/products/:productId">
    <ProductDetails addToCart={addToCart} data={data} />
</Route>

Notice how the route will be dynamic, we will be able to reference that :productId route parameter from within the component. With that we can pick the product from the data that the user wants to learn more about. We are also going to pass in the addToCart function so users can add the plant to their cart on this page as well.

Create the dynamic Link

In the Product component find the 'Full Details' anchor tag and refactor it to be a Link component with a dynamic value.

<Link to={`/products/${productId}`}>Full Details</Link>

Grabbing the :productId

In your ProductDetails component you can access the route param with useParams which is a function from react-router-dom (NOT 'react'). Use it like this to extract the id.

import { useParams } from 'react-router-dom'

/* previously written code */

const { productId } = useParams()

Assignment