react-smart-text
v1.1.0
Published
Replace meaningful substrings with React components.
Downloads
35
Readme
react-smart-text
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 [email protected]. Yours is [email protected].
</SmartText>
export default App
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/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>
)
}
}
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.
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,
componentProps: {
onClick: () => console.log('AEIOU'),
},
},
]
const App = () =>
<SmartText replacements={replacements}>
My email address is [email protected]. Yours is [email protected].
</SmartText>
export default App
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