martinkr/next-export-i18n

how to change "dir" in <body> element in the "_document" file

megetron opened this issue · 2 comments

hey,
i am trying to change the direction of the html based on the changing language.
in the _document.js file i have placed this:

import useLanguageQuery from "next-export-i18n";
const [query] = useLanguageQuery();

but then i get:

1 of 1 unhandled error
Server Error
TypeError: next_export_i18n__WEBPACK_IMPORTED_MODULE_2___default is not iterable (cannot read property Symbol(Symbol.iterator))

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source

pages/_document.js (3:16) @ eval

  1 | import Document, { Html, Head, Main, NextScript } from 'next/document';
  2 | import useLanguageQuery from "next-export-i18n";
> 3 | const [query] = useLanguageQuery();
    |                ^
  4 | 
  5 | 
  6 | class CustomDocument extends Document {

do i miss something?

Hi @megetron ,

Thank you for reaching out.

I am not exactly sure about your code, but from the code snippet, it looks like you are trying to call the useLanguageQuery-hook from outside a function component.

Only Call Hooks from React Functions
Don’t call Hooks from regular JavaScript functions. Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks (we’ll learn about them on the next page).

https://reactjs.org/docs/hooks-rules.html

Cheers,

Martin

you can achieve changing the dir element with minimal document node query with the following code:

import { useLanguageQuery } from "next-export-i18n";
import { useEffect } from "react";
const [query] = useLanguageQuery();
useEffect(() => {
    console.log(query)
    let dir = query?.lang == "ar" ? "rtl" : "ltr";
    let lang = query?.lang == "ar" ? "ar" : "en";
    document.querySelector("html").setAttribute("dir", dir);
    document.querySelector("html").setAttribute("lang", lang);
  }, [query]);

note in my example i am changing base on "Arabic language" "ar" , alter the code to your needs