Next Navigation using Next File-based-routing

clock icon

asked 2 months ago Asked

message

1 Answers

eye

28 Views

I have two different CSS files. One for English and One for Arabic. I am using next-i18next for internationalized routing in my next js App.

What I want is to load the CSS files based on the route. I have managed to make it work in my local system with this below code but when I host it in vercel It gives me an Error that both style.css and style-rtl.css are bundled as one.

1 Answers

When hosting your Next.js application on Vercel, the styling can sometimes be bundled into a single file due to the way Vercel optimizes and builds the project. To load CSS files based on the route in a Next.js application with different styles for English and Arabic versions, you can follow these steps:

1. Instead of directly importing the CSS files in your components or pages, you can dynamically load the CSS files based on the route using `useEffect` and `useRouter` from Next.js.

2. Here's a sample implementation of how you can achieve this:

```jsx
// components/Layout.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';

const Layout = ({ children }) => {
const router = useRouter();

useEffect(() => {
if (router.locale === 'ar') {
import('../styles/style-rtl.css');
} else {
import('../styles/style.css');
}
}, [router.locale]);

return (


{children}


);
};

export default Layout;
```

3. In this example, the `Layout` component dynamically imports the appropriate CSS file based on the current locale using the `router.locale` provided by `next-i18next`.

4. Ensure that your Next.js configuration and `next.config.js` are correctly set up to handle internationalized routing and CSS imports.

5. Finally, deploy your application to Vercel and check if the CSS files are loaded correctly based on the route/locale without being bundled into a single file.

By dynamically importing the CSS files based on the route/locale in your Next.js application, you can have separate styles for different languages while ensuring they are loaded appropriately on Vercel without being bundled together.

Write your answer here

Top Questions