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.

2
  • 1
    Does this answer your question? Dynamically load a stylesheet with React Commented Aug 19, 2022 at 18:09
  • @isherwood Yes! The answer looks promising thanks. I decided to drop bootstrap alltogether and use vanilla flexbox instead. Commented Aug 21, 2022 at 2:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @navid abbasnejad very clear answer. Can I lazy load the layout components?
Yes, you can lazy load the layout components using React's lazy loading and Suspense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.