0

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?

Hans
  • 2,674
  • 4
  • 25
  • 48

1 Answers1

1

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)
ravibagul91
  • 20,072
  • 5
  • 36
  • 59