Reputation: 525
I have a nextJS project that is structured such that the lang only affects the blog section of the project. I am having a problem changing the lang attribute in layout.tsx
appropiately according to the lang.
The directory structure is something like this :
src
[lang]/blog/page.tsx
home/page.tsx
layout.tsx
here is the code of the layout.tsx
export default function RootLayout({
children
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={`overflow-x-hidden`}>
{children}
</body>
</html>
);
}
in case, the blog page, has a fr
lang. I would need the lang value in layout.tsx to be fr
instead of en
. How can I achieve this?
NB: the layout.tsx is a server component, hence rendered in serverside, and I would love to keep it that way.
I am using nextJS 13
Upvotes: 1
Views: 1098
Reputation: 525
I figured out the solution to my problem, using useEffect()
to set the appropiate lang
In the [lang]blog
directory, I created a file sections.tsx
, separate from page.tsx
, reason being, I would need page.tsx to be strictly a server component, and here is where I would fetch my blog data. the sections.tsx
would contain all the section components of the blog page, and could be a client component since we are using useEffect
here, specified with "use client"
so the result would be something like this :
[lang]/blog/page.tsx
...
...
const Blog = async(props: Props) => {
const lang = props.params.lang;
const articles = await fetchArticles(lang)
return (
<main>
<Sections
articles={articles}
lang={lang}
/>
</main>
);
};
[lang]/blog/sections.tsx
"use client"
...
...
const Sections:React.FC<sectionProps> = ({
articles,lang
}) => {
useEffect(() => {
if(lang){
document.documentElement.setAttribute("lang", lang); //set the lang here
}
}, [lang])
return(
<>
<SectionOne/> //sections here
....
</>
)
}
I hope this can help someone else in the same situation.
Upvotes: 1