In Next.js, you can achieve similar routing functionality using the file-based routing system. Each page in Next.js corresponds to a file in the pages directory. Let's go through how you can implement the routes you mentioned in your React Router code:
- Create a file named
index.js(orindex.tsxfor TypeScript) in thepagesdirectory for the Home page:
// pages/index.js
import Home from '../components/Home';
export default Home;
- Create a file named
search.js(orsearch.tsxfor TypeScript) in thepagesdirectory for the search page:
// pages/search.js
import { useRouter } from 'next/router';
import Home from '../components/Home';
const SearchPage = () => {
const router = useRouter();
const { search } = router.query;
// You can use the 'search' query parameter here
return <Home />;
};
export default SearchPage;
- Create a file named
top_sold.js(ortop_sold.tsxfor TypeScript) in thepagesdirectory for the top sold page:
// pages/top_sold.js
import Home from '../components/Home';
export default Home;
- Create a file named
recent_added.js(orrecent_added.tsxfor TypeScript) in thepagesdirectory for the recent added page:
// pages/recent_added.js
import Home from '../components/Home';
export default Home;
- Create a file named
faq.js(orfaq.tsxfor TypeScript) in thepagesdirectory for the FAQ page:
// pages/faq.js
import { useRouter } from 'next/router';
import FAQ from '../components/FAQ';
const FAQPage = () => {
const router = useRouter();
const { section } = router.query;
// You can use the 'section' query parameter here
return <FAQ />;
};
export default FAQPage;
- Create a file named
client.js(orclient.tsxfor TypeScript) in thepagesdirectory for the profile page:
// pages/client.js
import { useRouter } from 'next/router';
import Profile from '../components/Profile';
const ProfilePage = () => {
const router = useRouter();
const { username, type, search } = router.query;
// You can use the 'username', 'type', and 'search' query parameters here
return <Profile />;
};
export default ProfilePage;
By creating these files, you define the different routes and corresponding components in the pages directory of your Next.js project. Next.js will automatically handle the routing based on the file structure.
Note that the code examples assume you have separate components (Home, FAQ, and Profile) that correspond to the different pages.
With this file-based routing approach, you can achieve similar functionality to the React Router code you provided. Remember to import and use the necessary hooks (useRouter from next/router) to access the query parameters and implement the logic as needed in each page component.
Top comments (0)