Ad

React-intl: Change Div Direction Based On Current Locale

- 1 answer

So, here is my App component:

const App = () => {
  const [lang, setLang] = useState("en");

  return (
    <IntlProvider
      locale={lang}
      key={lang}
      messages={lang == "en" ? englishMessages : arabicMessages}
    >
      <AppBar>
        <LangSwitch
          checked={lang == "en"}
          onChange={() => setLang(lang == "en" ? "ar" : "en")}
        ></LangSwitch>
      </AppBar>
      <Game />
    </IntlProvider>
  );
};
ReactDOM.render(<App />, document.getElementById("root"));

and, this is my Game component:

const Game = ()=>
   (<div direction = "???">
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>)

How can I read the current value of locale-set in the parent component of IntlProvider- inside child component of Game and set the property direction accordingly?

Ad

Answer

You need to pass state lang to your Game component,

<Game lang={lang}/>

And your Game component should be,

const Game = (props)=> ( //provide props argument here
   <div direction ={props.lang === 'en' ? 'ltr' : 'rtl'}>  //check your condition
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>
)

Update

Another way is wrapping your component with injectIntl HOC.

import {injectIntl} from 'react-intl';

const Game = ({intl})=> {
  console.log(intl.locale)
  return ( 
   <div direction ={intl.locale === 'en' ? 'ltr' : 'rtl'}>  //check your condition
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>
  )
}

export default injectIntl(Game)
Ad
source: stackoverflow.com
Ad