Skip to content

Commit

Permalink
Merge pull request #1061 from aralroca/add-hoc-to-fix-client-componen…
Browse files Browse the repository at this point in the history
…ts-in-next-translate-plugin

add hoc to fix client components in next-translate-plugin
  • Loading branch information
aralroca authored Jun 8, 2023
2 parents bc65924 + 8ca242e commit 5bed0eb
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "next-translate",
"version": "2.0.6",
"version": "2.3.0-canary.3",
"description": "Tiny and powerful i18n tools (Next plugin + API) to translate your Next.js pages.",
"license": "MIT",
"keywords": [
Expand Down
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ declare global {
var __NEXT_TRANSLATE__: {
namespaces: Record<string, I18nDictionary>
lang: string
pathname?: string
}

namespace NodeJS {
Expand Down
59 changes: 59 additions & 0 deletions src/withTranslationClientComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React, { useEffect, useReducer } from 'react'
import type { LoaderConfig } from '.'

/**
* @description HOC for internal use only (used by next-translate-plugin)
*/
export default function withTranslationClientComponent<
P extends JSX.IntrinsicAttributes
>(
Component: React.ComponentType<P>,
i18nConfig: LoaderConfig
): React.ComponentType<P> {
function WithTranslation(props: P) {
// @ts-ignore
const forceUpdate = useReducer(() => [])[1]
const isClient = typeof window !== 'undefined'

if (isClient && !window.__NEXT_TRANSLATE__) {
window.__NEXT_TRANSLATE__ = {
lang: i18nConfig.defaultLocale!,
namespaces: {},
}
update(false)
}

if (isClient && !window.i18nConfig) {
window.i18nConfig = i18nConfig
}

useEffect(update)

function update(rerender = true) {
const el = document.getElementById('__NEXT_TRANSLATE_DATA__')

if (!el) return

const { lang, ns, pathname } = el.dataset as {
lang: string
ns: string
pathname: string
}

const shouldRerender =
lang !== window.__NEXT_TRANSLATE__.lang ||
pathname !== window.__NEXT_TRANSLATE__.pathname

window.__NEXT_TRANSLATE__ = { lang, namespaces: JSON.parse(ns), pathname }

if (shouldRerender && rerender) forceUpdate()
}

return <Component {...props} />
}

const displayName = Component.displayName || Component.name || 'Component'
WithTranslation.displayName = `withTranslationClientComponent(${displayName})`

return WithTranslation
}

0 comments on commit 5bed0eb

Please sign in to comment.