Alright, I need some assistance from the js experts out there. Here’s my problem:
I receive an object from a CMS which contains two strings inside:
{pageContent.title}
Inside the object I get:
"title":{
"_type":"localeString"
"en":"Privacy Policy"
"es":"Política de Privacidad"
}
Each string represents a locale, and the page needs to render the correct one depending on the current locale. For that I’m using a simple router hook:
const router = useRouter()
const locale = router.locale
So now locale
returns either en
or es
To render the object on the page I’d do:
{pageContent.title.es}
for spanish and {pageContent.title.en}
for English, and so on.
However, I need the .es
and .en
part to be dynamic, and pick up that value from locale
since now there are only two languages, but more will be added in the future.
I found a very hacky solution that works but I’d prefer something more elegant.
First, I join both, but using the object partial name as a string. Then I remove the ” (unstringing it)
let localeTitle = 'pageContent.title.' + locale
localeTitle = localeTitle.replace(/"/g, '')
Then on the page, I eval() that new string:
{eval(localeTitle)}
Now, I know this isn’t the correct or best way of doing this.
And, before you ask why I’m not getting the corresponding language directly on the query, I tried. I’m using getStaticProps
to fetch the data, which doesn’t allow hooks to be used so I can’t access the locale
from the router.
Any ideas?