0

Twitter Bootstrap v5 provides two different css files for LTR vs RTL.

If I want to use the regular LTR version I can be import it in my index.ts as follows:

import 'bootstrap/dist/css/bootstrap.min.css';      // Stylesheet
import 'bootstrap/dist/js/bootstrap.bundle.min';    // Javascript

And if I want the RTL version I can imported as so:

import 'bootstrap/dist/css/bootstrap.rtl.min.css';  // Stylesheet
import 'bootstrap/dist/js/bootstrap.bundle.min';    // Javascript

I'm also using react-i18next to switch between Arabic and English translations to propagate the proper text in my components and detect the current language.

const { t, i18n } = useTranslation();
const language = i18n.resolvedLanguage;    // to detect the current language
<h1>{t('hello')}</h1>                      // to render the proper translation

I have no issues in my translations. What I want to achieve is to dynamically import the proper css during runtime according to the currently resolved language. If the language is Arabic I want to import the rtl css; otherwise, I want to import the regular ltr css.

I couldn't find an easy way to achieve this. I tried many different approaches using lazy and suspense but end up loading both files after I switch. I have also used react-helmet to switch the href of the link tag but can't achieve this in a clean way. Either errors or warnings in my console. The only work around I could implement is loading the css from a CDN and switch with helmet.

Anyone can suggest a clean way of dynamically load the proper CSS. Thanks.

isherwood
  • 58,414
  • 16
  • 114
  • 157
moeabdol
  • 4,779
  • 6
  • 44
  • 43
  • 1
    Does this answer your question? [Dynamically load a stylesheet with React](https://stackoverflow.com/questions/28386125/dynamically-load-a-stylesheet-with-react) – isherwood Aug 19 '22 at 18:09
  • @isherwood Yes! The answer looks promising thanks. I decided to drop bootstrap alltogether and use vanilla flexbox instead. – moeabdol Aug 21 '22 at 02:40

1 Answers1

1

You can use 2 other components for this

for rtl language

import App from "./App";
import 'bootstrap/dist/css/bootstrap.rtl.min.css'

function LayoutRtl() {
  return (<App />)
}

export default LayoutRtl

for ltr language

import App from "./App";
import 'bootstrap/dist/css/bootstrap.min.css';
function Layout() {

  return (<App />)
}

export default Layout

and for calling those

  const { i18n } = useTranslation();
  const language = i18n.language; 
  return language!=="fa" /* rtl language code */?( <Layout />):(<LayoutRtl />);

I tried this and it worked