react-text-subst
How will you add i18n support in following cases?
<span>Hello <span>username</span>!</span>
<span> By clicking “Sign up” you agree to our <a ="...">terms of service</a> and...</span>
Sure, you just can split texts in parts, but that parts would be translated not properly.
Here is a solution:
import TextSubst from 'react-text-subst'; return <TextSubst => Hello @user! </TextSubst>;
<TextSubst => By clicking “Sign up” you agree to our @linkterms of service and...</TextSubst>
Now you can simply add i18n to patterns and translate them.
Install
npm i --save react-text-subst
Pattern syntax
Pattern text has following special tokens:
@[foo]
- inline node. Render corresponding standalone value, element or component.@[foo[
- start block node. Render a component wrapped around block's content.]]
- end corresponding block node.
Notice: Since React has special props
key
andref
, you shouldn't use such names in pattern.
Nodes
So, there are few types of nodes. Nodes of any type can repeat or share its' names - everything is up to you.
@[foo]
Inline Inline node can render anything what React can render as a node, or component. The last will receive following property:
name
- corresponding node name (foo
in example).
<TextSubst = = => foo @bar lol @baz@qux</TextSubst>// <>// foo {something} lol <b>{something}</b><b>value of qux</b>// </>
@[foo[...]]
Block Block node can only render a component. It will receive following properties:
name
- corresponding node name (foo
in example).children
- rendered content of the block.
Blocks can be nested.
<TextSubst = => lorem @bipsum @idolor sit amet @iconsectep@bture</TextSubst>// <>// lorem <b>ipsum <i>dolor</i> sit</b> amet <i>consectep<b>ture</b></i>// </>
<TextSubst => lorem @fooipsum @foodolor sit amet</TextSubst>// <>// lorem <span>ipsum <span>dolor</span> sit</span> amet// </>
const Link = name children <a =>children</a>;return <TextSubst = => lorem @fooipsum dolor @barsit amet </TextSubst>;// <>// lorem <a href={URL.foo}>ipsum</a> dolor <a href={URL.bar}>sit</a> amet// </>
API
Properties
-
children
- pattern string to render, only single string is acceptable:<TextSubst>Lorem ipsum dolor</TextSubst><TextSubst>'Lorem ipsum dolor'</TextSubst><TextSubst></TextSubst> -
...
rest - value, element or component to render nodes with corresponding name.Notice: You cannot use React specific props like
key
orref
for values.
License
This package is under MIT License