I am changing language dynamically, so I want to switch from rtl to ltr and vice-versa.
I am using bootstrap-rtl for rtl support.
Here is my code:
componentWillReceiveProps(nextProps) {
if (this.props.isRTL !== nextProps.isRTL) {
if (nextProps.isRTL) {
require('bootstrap-rtl/dist/css/bootstrap-rtl.css');
} else {
//what should i do here????????????
}
}
}
So, when component first renders, english
is selected. So, isRTL is false
. As a result require('........bootstrap-rtl.css')
doesn't come to play.
Now, When I change language to arabic
, isRTL becomes true
and bootstrap-rtl.css
is required
. Now, I can see everything rtl
.
Now, when I again change language to english
, isRTL becomes false
, but bootstrap-rtl.css
is not unrequired
, so still I see everything rtl
.
Can someone suggest me the solution or even alternate solution is acceptable for me.
I don't know if there's anything special about how React require
s stuff, but in general, loading a stylesheet basically means inserting a <link>
element that refers to it. You can "unload" the stylesheet by removing the element that refers to it. You might also be able to disable it by setting its rel
attribute to something besides "stylesheet".
But any change requires first finding that element. It's kinda messy.
If you want to be able to switch from RTL to LTR and back on the fly, there's a better way than "unloading" the RTL CSS. There's a fork of bootstrap-rtl called bootstrap-rtl-ondemand which, instead of always applying RTL styles, only applies them when the document's direction is set to "rtl".
Install the package above (or if you don't use NPM, get at least the CSS files from the package's Github repo), and set things up so that the CSS loads after Bootstrap's.
Now you can switch between RTL and LTR basically at will. Your method above becomes as simple as:
componentWillReceiveProps(nextProps) {
if (this.props.isRTL !== nextProps.isRTL) {
document.documentElement.dir = (nextProps.isRTL) ? 'rtl' : 'ltr';
}
}