react-smart-text
Replace meaningful substrings with components.
This is a complete example of replacing email addresses with mailto anchors.
// This is what we're hunting in the text.const emailRegex = /\w+@.+?\./g // This is what we want to replace matches with.const Email = <a href=`mailto:`>propstext</a> const App = <SmartText regex=emailRegex component=Email> My email address is dingo@bingocom Yours is you@the-zoocom </SmartText>
Result
Usage
Render a plain string within <SmartText />
and substrings matching a pattern
will be replaced by a custom component.
Props
regex - Provide a regular expression describing the substring(s) you wish to replace.
component - The component regex matches will be replaced with. Instances will be passed the props
- result - RegExp.exec result
- text - the plain text of the match
- extra props you need passed down (like event handlers), see "componentProps"
outerComponent (optional) - The outer component all other nodes will be
contained within. Thid defaults to a plain <div />
.
Installation
yarn add react-smart-text
Examples
Using componentProps
const barRegex = /bar/gconst Bar = <div onClick=propsonClick> propstext </div> Component { console } { const barProps = onClick: thishandleBarClick return <SmartText regex=barRegex component=Bar componentProps=barProps> foo bar baz </SmartText> }
You can also include componentProps
when using multiple replacements.
Multiple Replacement Types
If you want to replace multiple types of strings, provide an array of replacments.
const emailRegex = /\w+@.+?\./gconst Email = <a href=`mailto:`>propstext</a> const vowelRegex = /[aeiou]/giconst Vowel = <span className="vowel">*</span> const replacements = regex: emailRegex component: Email regex: vowelRegex component: Vowel componentProps: console const App = <SmartText replacements=replacements> My email address is dingo@bingocom Yours is you@the-zoocom </SmartText>
Result
Note that replacements only happen on text nodes. If a replacment has already happened for a section of text, it will not be processed again. This is why the vowels are visible in the emails above. This may change in a future version.
Test
yarn test
kickstarted by npm-boom