A simple library for rendering plaintext templates to React elements.
Install the library and import it:
yarn add react-text-templates
import renderTemplate from 'react-text-templates'
renderTemplate(template, tokens)
Render a template that contains string and component tokens:
import renderTemplate from 'react-text-templates'
const Link = ({ href, children }) => <a href={href}>{children}</a>
const template = 'We found {COUNT} instances of the term {TERM} in the article.'
const tokens = {
COUNT: 42,
TERM: <Link href="/term/presence">Presence</Link>,
}
export default () => <p>{renderTemplate(template, tokens)}</p>
If you rendered the exported component, it would produce the following DOM:
<p>
We found 42 instances of the term
<a href="/term/presence">Presence</a>
in the article.
</p>
Many times, the template
string in the example above would come from an external data store, like a database or CMS. With this library, we can define tokens of mixed type (string and jsx) and inject them into these external templates as if we were dealing with simple strings.