Nextjs useContext to change language html in layout.tsx from child component
BlackMan
Posted on September 26, 2023
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:
I has created 2 file: context.tsx, child.tsx
Make a context.tsx:
import { Context } to child.tsx
import { Context } and wrap Context.Provider to child.tsx
This is result when onclick button to change lang in layout
Fullcode:
context.tsx
"use client"
import { createContext } from 'react'
export const Context = createContext({
language: "vi",
setLanguage: function (value:any) {
return value
}
})
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>
</>
)
}
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>
)
}
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>
)
}
💖 💪 🙅 🚩
BlackMan
Posted on September 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
nextjs Nextjs useContext to change language html in layout.tsx from child component
September 26, 2023