DEV Community

BlackMan
BlackMan

Posted on

Nextjs useContext to change language html in layout.tsx from child component

The useContext() hook in React allows function components to access the context value for a context object. It takes the context object as the only argument and returns the current context value as given by the nearest context provider.

This way to useContext change html lang='vi' to lang='en' in layout.tsx

Firts please see structure:
Image description
I has created 2 file: context.tsx, child.tsx
Make a context.tsx:
Image description
import { Context } to child.tsx

Image description
Please see a page.tsx

Image description

import { Context } and wrap Context.Provider to child.tsx

Image description
This is result when onclick button to change lang in layout

Image description

Image description

Fullcode:
context.tsx

"use client"
import { createContext } from 'react'

export const Context = createContext({
  language: "vi",
  setLanguage: function (value:any) {
    return value
  }
})
Enter fullscreen mode Exit fullscreen mode

child.tsx

"use client"
import { useContext } from 'react'
import { Context } from "./context";
export default function Child() {
    const { language, setLanguage } = useContext(Context)
    return (
        <>
            <h2 className=' text-xl'>From child {language}</h2>
            <div className=' flex flex-row space-x-2'>
                <button onClick={() => { setLanguage('En') }}>Change EN</button>
                <button onClick={() => { setLanguage('Vi') }}>Change VI</button>
            </div>
        </>
    )

}
Enter fullscreen mode Exit fullscreen mode

page.tsx

"use client"
import Image from 'next/image'
import Child from './child'
import { Context } from "./context";
import { useContext } from 'react'

export default function Home() {
  const { language, setLanguage } = useContext(Context)
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h1 className=' text-2xl'>From Home: {language}</h1>
        <Child></Child>
    </main>
  )
}

Enter fullscreen mode Exit fullscreen mode

layout.tsx

"use client"
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import { Context } from "./context";
import { useState } from 'react'
const inter = Inter({ subsets: ['latin'] })


export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [language, setLanguage] = useState('vi')
  const value = {
    language, setLanguage
  }
  return (
    <Context.Provider value={value}>
    <html lang={language}>
      <body className={inter.className}>{children}</body>
    </html>
    </Context.Provider>


  )
}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
chungleba profile image
BlackMan

tèn ten

Collapse
 
peter_sang profile image
SangMai1

Nice