JSX Interpolation
JSX is a great and widely adopted syntax extension for Javascript.
However, even though it looks like HTML JSX is actually
a Javascript object and it has to be rendered.
So, if you have HTML source code as string,
the only way to inject that HTML code is to use
dangerouslySetInnerHTML
property.
As the property name suggests is not ideal and dangerous since you don't have control over what's going to be rendered and this can lead to XSS attacks.
Problem
When an entry contains html elements it gets complicated to generate translation text.
A typical use case of this property is having a link in a translation string.
<p>
Please click <a href="#path" onClick={handleClick}>here</a> to download
<code>build-x64.zip</code> file!
</p>
As you can see, the real fun begins
when you have an event handler like onClick
, where
even dangerouslySetInnerHTML
property is not the direct
solution.
How Lisan solves it?
lisan-compiler
, with >v0.0.40
takes returnArray
option.
This option converts dictionary entries to Arrays, where JSX can easily join and render them.
Example
- Lets assume we have a translation file like below:
// translations/main.json
{
"entries": {
"word.here": "here",
"download.text": "Please click ${downloadLink} to download ${codeElement} file!"
}
}
- We compile it using
--returnArray
flag.
lisan compile --returnArray --module=esm
- Generated dictionary looks like below.
// dictionaries/main.js
export default {
entries: {
'download.text': ({ downloadLink, codeElement }) => [
'Please click ',
downloadLink,
' to download ',
codeElement,
' file!',
],
'word.here': ['here'],
},
};
- We use generated dictionary in our JSX syntax like below:
<p>{t("download.text", {
downloadLink: <a href="#path" onClick={handleClick}>{t("word.here")}</a>,
codeElement: <code>build-x64.zip</code>
})}<p>