Day-11 React with Me
Building the Homepage and Understanding RouterLink and NavLink in React
Creating the Homepage with Filtering and Search Functionality
In the development of our food app, we've created a dynamic homepage that fetches restaurant data and allows users to filter and search for restaurants based on their preferences. Let's dive into the details of how we implemented this functionality:
Fetching Restaurant Data We fetch restaurant data from an API endpoint using the fetchData function. This function retrieves data and sets the list state with the fetched restaurants.
Filtering Restaurants We provide two filter options: "Top Rated" and "Delivery time". The applyFilter function filters the list of restaurants based on the selected tab and updates the filteredList state accordingly.
Searching Restaurants We include a search bar where users can enter keywords to search for specific restaurants. The searchText state is updated as the user types, and the filteredList is updated to show only restaurants that match the search query.
Implementation Details We use the Filters component to create filter buttons for "Top Rated" and "Delivery time". The Link component from react-router-dom is used to link each restaurant card to its detailed page.
Understanding RouterLink and NavLink
In React, RouterLink and NavLink are components provided by the React Router library for handling navigation between different parts of our app. Here's a brief overview of each:
RouterLink: This component is used to create links within our app. It is similar to the HTML tag but is specifically designed for use with React Router. It helps in maintaining the single-page application (SPA) behavior by preventing full-page reloads when navigating between routes.
NavLink: NavLink is a special type of RouterLink that allows us to add styling to the active link based on the current route. This is useful for highlighting the current page or section in the navigation menu, providing a better user experience.
const appRouter = createBrowserRouter([
{
path: "/",
element: <AppLayout />,
children: [
{
path: "/",
element: <Homepage />,
},
{
path: "/about",
element: <About />,
},
{
path: "/contact",
element: <Contact />,
},
{
path: "/restaurants/:resId",
element: <NewMenu />,
},
],
errorElement: <Error />,
},
]);
/*Router Configuration: Using createBrowserRouter from
react-router-dom, you define your app's routes. Each route
is associated with a specific component (Homepage, About, Contact, NewMenu)
that should be rendered when the corresponding path is matched.*/
const root = ReactDom.createRoot(document.getElementById("root"));
root.render(<RouterProvider router={appRouter} />);
For reference -
https://github.com/piyusss11/Foodie-Boodie-App-React