Product Page in Redux
In this lesson we will make a separate page to display information about a specific product.
Let's open our product app and create a file ProductPage.jsx in the products folder. As you remember, each of our products has a unique id. Thanks to this id, we will be able to generate a unique page URL for each product. Traditionally, it will look like: /products/id123. And the id will be contained in its dynamic part (we will deal with the route itself a little later).
So, let's create an empty component ProductPage.jsx in ProductPage.jsx:
export const ProductPage = () => {}
The first thing we'll do here is use the useParams hook to pull in the dynamic portion of the URL for the product page we're on:
export const ProductPage = () => {
let params = useParams()
const { productId } = params
}
Next, using the received id, we will search for the required product in the products slice in the store, using the already familiar useSelector hook:
const product = useSelector((state) =>
state.products.find((product) => product.id === productId)
)
Let's not forget to import both hooks into the file:
import { useSelector } from 'react-redux'
import { useParams } from 'react-router-dom'
If the product we need is not available (for example, the user entered an incorrect address), then we will display information about this on the screen. At this step, the code for the ProductPage component should look like this:
export const ProductPage = () => {
let params = useParams()
const { productId } = params
const product = useSelector((state) =>
state.products.find((product) => product.id === productId)
)
if (!product) {
return <p>No such product</p>
}
}
And all that remains for us to do is to display the received product data in the layout:
return (
<div>
<h2>{product.name}</h2>
<p>Description: {product.desc}</p>
<p>Price: {product.price}</p>
<p>Amount:{product.amount}</p>
</div>
)
Open your application with students. In the students folder, create a file StudentPage.jsx, in which you will receive and display information about the selected student.
Using the react-redux hook useSelector get the required student information as shown in the tutorial.
Display the received information about the student on the screen in the component.