-
I am experimenting with the new NextJS internationalisation support, and I would like to add a dir attribute to the html tag and dynamically change it based on active locale, to properly support RTL languages. An example code would be appreciated. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 15 replies
-
In case you want to change HTML structure you need custom document. Create a file like -> pages/_document.js
For doing it inside a component. Try this. Using useRouter TestLocale.jsx
More info: https://nextjs.org/docs/advanced-features/i18n-routing#accessing-the-locale-information |
Beta Was this translation helpful? Give feedback.
-
I tried the snippet above and the dynamically (lang) attribute disappeared. Here is the updated snippet: // pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
const { locale } = this.props.__NEXT_DATA__;
const dir = locale === 'ar' ? 'rtl' : 'ltr';
return (
<Html lang={locale} dir={dir}>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
|
Beta Was this translation helpful? Give feedback.
-
to add dynamic changer use
|
Beta Was this translation helpful? Give feedback.
-
hey guys is there a possible way to add conditional css import my idea is to load diffrent css files based on the dir attribute so i there any possible way to do this mechanic in next js ?? currently i'm acheiving this using Head component by serving diffrent link tags when the locale is ar
but i dont know if this is good for performance or not |
Beta Was this translation helpful? Give feedback.
-
Dynamic html and script work fine for me import Document, {
Html, Head, Main, NextScript,
} from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
// locale is in ctx.locale
return { ...initialProps, locale: ctx?.locale || 'en' };
}
render = () => (
<Html dir={this.props.locale === 'fr' ? 'fr' : 'en'} lang={this.props.locale}>
<Head />
<body>
<Main />
<NextScript />
{this.props.locale === 'fr'
? (
<>
<script dangerouslySetInnerHTML={{
__html: 'french script',
}} />
</>
) : (
<script dangerouslySetInnerHTML={{
__html: 'english script',
}} />
)}
</body>
</Html>
)
}
export default MyDocument; |
Beta Was this translation helpful? Give feedback.
-
Using a functional Component you can just add following code, and for versions above 10 lang attribute is automatically handled.
|
Beta Was this translation helpful? Give feedback.
-
Also, there is a CSS hack to change the direction that may seems very basic but it's a life saver
|
Beta Was this translation helpful? Give feedback.
In case you want to change HTML structure you need custom document.
Create a file like -> pages/_document.js