1. Introduction
For a Vite-based React application, loading different theme CSS files based on locale dynamically is a bit different than in Create React App, especially because Vite doesn’t automatically copy files from public/
unless explicitly referenced.
Use dynamic import()
to load CSS modules from src/
instead of relying on public folder.
2. Directory Structure
src/ themes/ en.css ar.css App.jsx main.jsx
3. src/themes/en.css
body { direction: ltr; background-color: #e6f7ff; color: #111; font-family: sans-serif; }
4. src/themes/ar.css
body { direction: rtl; background-color: #fff5e6; color: #111; font-family: 'Tahoma', sans-serif; }
5. src/App.jsx
import { useEffect, useState } from 'react'; const App = () => { const [locale, setLocale] = useState('en'); useEffect(() => { async function loadTheme() { if (locale === 'ar') { await import('./themes/ar.css'); } else { await import('./themes/en.css'); } } loadTheme(); }, [locale]); return ( <div> <h1>{locale === 'ar' ? 'مرحبًا' : 'Hello'}</h1> <p>{locale === 'ar' ? 'اختر اللغة' : 'Choose a language'}</p> <button onClick={() => setLocale('en')}>English</button> <button onClick={() => setLocale('ar')}>العربية</button> </div> ); }; export default App;
6. src/main.jsx
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <App /> </React.StrictMode> );