Replace meaningful substrings with components.
This is a complete example of replacing email addresses with mailto anchors.
import React from 'react'
import SmartText from 'react-smart-text'
// This is what we're hunting in the text.
const emailRegex = /\w+@.+?\.(com)/g
// This is what we want to replace matches with.
const Email = (props) =>
<a href={`mailto:${props.text}`}>{props.text}</a>
const App = () =>
<SmartText regex={emailRegex} component={Email}>
My email address is dingo@bingo.com. Yours is you@the-zoo.com.
</SmartText>
export default AppResult
Render a plain string within <SmartText /> and substrings matching a pattern
will be replaced by a custom component.
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 />.
yarn add react-smart-text
const barRegex = (/bar/g)
const Bar = (props) => (
<div onClick={props.onClick}>
{props.text}
</div>
)
class Demo extends React.Component {
handleBarClick = () => {
console.log('Bar was clicked')
}
render () {
const barProps = {
onClick: this.handleBarClick,
}
return (
<SmartText regex={barRegex} component={Bar} componentProps={barProps}>
foo bar baz
</SmartText>
)
}
}If you want to replace multiple types of strings, provide an array of replacments.
import React from 'react'
import SmartText from 'react-smart-text'
const emailRegex = /\w+@.+?\.(com)/g
const Email = (props) =>
<a href={`mailto:${props.text}`}>{props.text}</a>
const vowelRegex = /[aeiou]/gi
const Vowel = (props) =>
<span className="vowel">*</span>
const replacements = [
{
regex: emailRegex,
component: Email,
},
{
regex: vowelRegex,
component: Vowel,
},
]
const App = () =>
<SmartText replacements={replacements}>
My email address is dingo@bingo.com. Yours is you@the-zoo.com.
</SmartText>
export default AppResult
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.
yarn test
kickstarted by npm-boom

