Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dom

reactjs

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?

like image 913
Ashraf Fayad Avatar asked Dec 12 '15 07:12

Ashraf Fayad


People also ask

Can we use body tag in React?

To add a class to the body element in React: Access the body element as document. body in useEffect or an event handler.

Can I use HTML tags in React?

By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML.


2 Answers

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' 
like image 61
Enrico Avatar answered Sep 29 '22 12:09

Enrico


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' } 
like image 37
Freezystem Avatar answered Sep 29 '22 11:09

Freezystem