How to replace parts of a string with a component?
I have this code which is obviously not working:
_.each(matches, (match) ->
string = string.replace(match, ->
<span className="match" key={i++}>{match}</span>
)
)
Because that would result into a string mixed with objects. Bad I know. But how can I add React components inside a string? All I want is to highlight parts of a string with a react component. A tough case to crack I guess.
something like this should work :
const escapeRE = new RegExp(/([.*+?^=!:$(){}|[\]\/\\])/g)
const safeRE = (string) => {
return string.replace(escapeRE, "\\$1")
}
class Hightlight extends Component {
static propTypes = {
match : PropTypes.string,
string : PropTypes.string,
}
render() {
return (
<span
dangerouslySetInnerHTML={{
__html : string.replace(safeRE(this.props.match), "<strong className\"match\">$1</strong>")
}} />
)
}
}
Yes, I've been thinking of abusing dangerouslySetInnerHTML but I do not like this idea. This method labelled as dangerously for good reasons.
Is there no way to teach React to parse jsx within a string? Have React parse i.E.
var example = "this one word <span className="match" key={i++}>hello</span> is highlighted"
and return this in a render method?
@binarykitchen You can construct React elements dynamically and that's what you need to do here, you just can't do it with only string replacement.
@syranide Yes, I already know that. My point is: wouldn't this be a nice JSX/React feature? Parse a string and turn any tags inside into child React components.
You can use the split function with a regex and then replace the captured parts, like so:
var parts = "I am a cow; cows say moo. MOOOOO.".split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
parts[i] = <span className="match" key={i}>{parts[i]}</span>;
}
return <div>{parts}</div>;
Let me know if that's unclear.
Parsing JSX at runtime is error-prone and slow, and can easily have security implications – it wouldn't inherently be any safer than dangerouslySetInnerHTML is.
that can be a bit of an issue with type case
— mlb
On 12 mars 2015, at 21:37, Ben Alpert [email protected] wrote:
You can use the split function with a regex and then replace the captured parts, like so:
var parts = "I am a cow; cows say moo. MOOOOO.".split(/(\bmoo+\b)/gi); for (var i = 1; i < parts.length; i += 2) { parts[i] = {parts[i]}; } return
{parts}; Let me know if that's unclear.— Reply to this email directly or view it on GitHub.
I ran into this issue as well when trying to highlight parts of a string programatically (i.e. replace with <span> tags). I ended up creating a module based on @spicyj's solution above. For anyone interested: iansinnott/react-string-replace
@iansinnott Thanks for sharing that. I started using it then realized I'm going to need the full String.prototype.replace API (needed access to the individual matching groups for a regexp within the replace function). I realized the change will be more than a simple patch (and require an API change) so I created a new repo: https://github.com/oztune/string-replace-to-array
If react-string-replace doesn't fit your requirements:
https://github.com/EfogDev/react-process-string
The following worked for me as way to highlight keyword(s) within a string of text, without dangerously setting HTML:
/**
* Find and highlight relevant keywords within a block of text
* @param {string} label - The text to parse
* @param {string} value - The search keyword to highlight
* @return {object} A JSX object containing an array of alternating strings and JSX
*/
const formatLabel = (label, value) => {
if (!value) {
return label;
}
return (<span>
{ label.split(value)
.reduce((prev, current, i) => {
if (!i) {
return [current];
}
return prev.concat(<b key={value + current}>{ value }</b>, current);
}, [])
}
</span>);
};
formatLabel('Lorem ipsum dolor sit amet', 'dolor');
// <span>Lorem ipsum <b>dolor</b> sit amet</span>
I needed something like this for mentions matching some pattern so it can wrap multiple values and did some changes to the @richardwestenra solution. Maybe it will be useful for someone.
/**
* Find and highlight mention given a matching pattern within a block of text
* @param {string} text - The text to parse
* @param {array} values - Values to highlight
* @param {RegExp} regex - The search pattern to highlight
* @return {object} A JSX object containing an array of alternating strings and JSX
*/
const formatMentionText = (text, values, regex) => {
if (!values.length)
return text;
return (<div>
{text.split(regex)
.reduce((prev, current, i) => {
if (!i)
return [current];
return prev.concat(
values.includes(current) ?
<mark key={i + current}>
{current}
</mark>
: current
);
}, [])}
</div>);
};
const text = 'Lorem ipsum dolor sit amet [[Jonh Doe]] and [[Jane Doe]]';
const values = ['Jonh Doe', 'Jane Doe'];
const reg = new RegExp(/\[\[(.*?)\]\]/); // Match text inside two square brackets
formatMentionText(text, values, reg);
// Lorem ipsum dolor sit amet <mark>Jonh Doe</mark> and <mark>Jane Doe</mark>
I had a similar issue and I solved it with react portals, to easily find the node, I replaced the string with a div and rendered my react component using createPortal into that div.
@rmtngh I'm curious why you'd need to do that. It seems like it might be overkill. Are you interlacing non-react code?
Regarding solutions to this problem, I'd like to re-recommend string-replace-to-array (I'm the author). It's been battle and time-tested on multiple environments. It's also quite small (the entire library is this file https://github.com/oztune/string-replace-to-array/blob/master/string-replace-to-array.js).
Here's a usage example with regex:
import replace from 'string-replace-to-array'
// The API is designed to match the native 'String.replace',
// except it can handle non-string replacements.
replace(
'Hello Hermione Granger...',
/(Hermione) (Granger)/g,
function (fullName, firstName, lastName, offset, string) {
return <Person firstName={ firstName } lastName={ lastName } key={ offset } />
}
)
// output: ['Hello ', <Person firstName="Hermione" lastName="Granger" key={ 0 } />, ...]
@oztune Thanks for your reply, In this case I have a string of html markup coming from a wysiwyg editor of a CMS and I'd like to place react components in certain places inside that markup. Do you think it would be better to use a library instead of using portals? I think what portal does is to just render the component inside another node instead of nearest node which wouldn't be more expensive than rendering a normal component and the only extra step is to replace the string which can be done with native js replace. Am I missing anything? Will there be any advantages in using the library instead?
@rmtngh I'd say it depends on what you're trying to do. If you're just trying to sprinkle some React components in different areas of your DOM tree, and the tree isn't already being rendered with React, portals are the way to go. The method I mentioned is most useful when the parts you're trying to replace are already rendered inside of a React component.
Here's the code that returns an array of nodes given text and pattern:
const highlightPattern = (text, pattern) => {
const splitText = text.split(pattern);
if (splitText.length <= 1) {
return text;
}
const matches = text.match(pattern);
return splitText.reduce((arr, element, index) => (matches[index] ? [
...arr,
element,
<mark>
{matches[index]}
</mark>,
] : [...arr, element]), []);
};
Thank you @wojtekmaj My version for groups in pattern:
const replacePatternToComponent = (text, pattern, Component) => {
const splitText = text.split(pattern);
const matches = text.match(pattern);
if (splitText.length <= 1) {
return text;
}
return splitText.reduce((arr, element) => {
if (!element) return arr;
if(matches.includes(element)) {
return [...arr, Component];
}
return [...arr, element];
},
[]
);
};
const string = 'Foo [first] Bar [second]';
const pattern = /(\[first\])|(\[second\])/g;
replacePatternToComponent(string, pattern, <Component />);
Approach using typescript:
const formatString = (
str: string,
formatingFunction?: (value: number | string) => React.ReactNode,
...values: Array<number | string>
) => {
const templateSplit = new RegExp(/{(\d)}/g);
const isNumber = new RegExp(/^\d+$/);
const splitedText = str.split(templateSplit);
return splitedText.map(sentence => {
if (isNumber.test(sentence)) {
const value = values[Number(sentence)];
return Boolean(formatingFunction) ? formatingFunction(value) : value;
}
return sentence;
});
};
Example of use:
const str = '{0} test {1} test';
formatString(str, value => <b>{value}</b>, value1, value2);
Result:
<b>value1</b> test <b>value2</b> test
@rmtngh could you provide a sample of how you achieved the markup enrichment through createportal? I'm looking to do the same.