Manipulate the <html> or <body> tag in React

前端 未结 2 474
逝去的感伤
逝去的感伤 2021-02-01 20:29

What is the best way to manipulate the or tags in React?

For example, dynamically setting \'lang\' attribute or chan

相关标签:
2条回答
  • 2021-02-01 20:47

    It's ok to change the lang property directly and you may do so changing the value of document.documentElement.lang

    For example:

    var newLang = 'fr';
    ...
    document.documentElement.lang = newLang; // will set the lang property to 'fr'
    
    0 讨论(0)
  • 2021-02-01 20:51

    I've just encountered this use case where I want to modify the <html> lang attribute when language is switched by the user.
    React Helmet made this quite simple actually.

    Just get the lang from your react state and pass it to the Helmet component anywhere in your app:

    <Helmet htmlAttributes={{ lang : this.state.lang }}/> // with this.state = { lang : 'en' }
    
    0 讨论(0)
提交回复
热议问题