react-text-templates
v1.0.5
Published
Simple library to render plaintext templates to React elements
Downloads
97
Readme
react-text-templates
A simple library for rendering plaintext templates to React elements.
Getting started
Install the library and import it:
yarn add react-text-templates
import renderTemplate from 'react-text-templates'
renderTemplate(template, tokens)
Basic example
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>
Why is this useful?
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.