react-text-templates

1.0.5 • Public • Published

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.

Package Sidebar

Install

npm i react-text-templates

Weekly Downloads

23

Version

1.0.5

License

MIT

Unpacked Size

7.63 kB

Total Files

5

Last publish

Collaborators

  • pzhine