This video is available to students only

Creating Categories Page

In this lesson, we're going to create categories page

Creating categories page#

In the last lesson, we created ShowCourses component, which means we can show a list of courses at any page. We can easily create our categories page now. If you remember, our getCategory method takes an id and returns the cateogry with courses, so let's use it here.

Let's go to our agent.ts file, and inside Categories, we can add a new method called getCategory and pass id as a parameter. This will be of type number. We will use the getRequest and the response will be of type category, and url will be categories/id. Now we can make request for a category. What we need to do is create a new page and call it CategoryPage; import react and create CategoryPage function — let's export it as well. We can go to the App.tsx file and make a new Route with path, /category/:id. We need the id to be dynamic because we will use the id from the url and make a request accordingly. So we can use colon before the id, which makes it dynamic.


Coming back to the CategoryPage, we need to create a state called data where we will store our api response, so let's use useEffect hook and use agent.Categories.getCategory, then response and inside, setData to response. We need to pass categoryId to the function, so how can we do it? We need to use the id which is inside our url. react-router gives us useParams, which will give us access to the id param, so let's import it from react-router. Let's destructure it, and give it a type string because everything in our url is a string. Now inside our request, we can typecase the string into an integer using parseInt. Let's also pass id as dependency because we need to rerun this when the id changes. Now inside our return statement, we can copy stuff from Homepage and paste it here. Inside our h1, we can write, "Pick a course from your favorite category", and inside h2, we can write Let's also write a question mark which will make sure that it renders it only if it's available. We can also check if there are courses inside data, by using ternary operator. When there's length which means if it's more than zero, we will map it. Otherwise, we can show, "No Courses found in this Category!". I want to make a few changes to the course.scss file. I want to make the flex direction to be column and remove this wrap because we made ShowCourses a different component.

Start a new discussion. All notification go to the author.