Skip to content

How to dynamically set dir attribute based on locale in NextJS 10? #19049

Answered by puntope
oahmaro asked this question in Help
Discussion options

You must be logged in to vote

In case you want to change HTML structure you need custom document.

Create a file like -> 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)
        // locale is in ctx.locale

        return { ...initialProps, locale: ctx?.locale || 'es' }
    }
   
    render = () => (
        <Html dir={this.props.locale === 'ar' ? 'rtl': 'ltr'} lang={this.props.locale}>
            <Head />
            <body>
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

export default …

Replies: 7 comments 15 replies

Comment options

You must be logged in to vote
11 replies
@monafHorany
Comment options

@monafHorany
Comment options

@dmytromod
Comment options

@AbdElRahman111192
Comment options

@foadtkf
Comment options

Answer selected by oahmaro
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@markus-azer
Comment options

@Mood-al
Comment options

@m5m5h
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@wedhimd
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet