I'm using react-i18next: "11.16.9" for translating my react project . It works well for the .js and .jsx files . This is the format I'm using
const { t } = useTranslation();
<th>{t('constant.name')}</th>
I got stuck in a scenario where I have some html content inside a .md extension file , Which I later render in my react component using dangerouslySetInnerHTML .
---
path: "/404"
title: "404 - This page doesn't exist"
---
<section class="section section--gradient pb-0">
<div class="container apis-content">
<div class="documentation-links">
This text needs to be translated
</div>
</div>
</section>
this is my 404.md file . Which I render like
<div id="main" dangerouslySetInnerHTML={{ __html: t(content.html) }} />
Since it is an .md file I couldn't use any import any constant or hooks or hoc . How can I use constant variables like the {t('constant.name')} inside the .md file ? any work around for this ? or am I missing anything ?
FYI: I can't convert the .md files as react files since there are lot many and I'm running out of time
You could create a React hook that injects the translation by processing the HTML content using your own tag:
function useHTMLTranslation() {
const { t } = useTranslation();
const newT = React.useCallback(
(html = "") => {
let key = html; // fallback
const regex = /(?<=\[TRANS\]).*(?=\[\/TRANS\])/g;
// probably you need to adjust this if you want support multiple TRANS tags
const capture = html.match(regex);
if (capture.length > 0) {
key = capture[0];
return html.replace(`[TRANS]${key}[/TRANS]`, t(key));
}
return t(key);
},
[t]
);
return newT;
}
template:
---
path: "/404"
title: "404 - This page doesn't exist"
---
<section class="section section--gradient pb-0">
<div class="container apis-content">
<div class="documentation-links">
[TRANS]constant.name[/TRANS]
</div>
</div>
</section>
usage:
const { t } = useHTMLTranslation();
<div id="main" dangerouslySetInnerHTML={{ __html: t(content.html) }} />