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

≯℡__Kan透↙ 提交于 2020-06-24 07:16:12

问题


What is the best way to manipulate the <html> or <body> tags in React?

For example, dynamically setting 'lang' attribute or change classes?

<html lang="en" class="ltr">

I could do that using raw DOM manipulation. But is this the right way?


回答1:


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' }



回答2:


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'


来源:https://stackoverflow.com/questions/34237420/manipulate-the-html-or-body-tag-in-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!