Replace part of string with tag in JSX
When you pass a JSX element to replace()
as the second argument, that element is converted to a string because replace()
expects a string as a second argument. What you need to do is convert your string to an array of strings and JSX elements. So your result
variable should contain something like ['Lorem ', <div className="spacer"></div>, ' ipsum']
.
Something like this:
function flatMap(array, fn) {
var result = [];
for (var i = 0; i < array.length; i++) {
var mapping = fn(array[i]);
result = result.concat(mapping);
}
return result;
}
var Comp = React.createClass({
render: function () {
var result = 'Lorem : ipsum';
result = flatMap(result.split(':'), function (part) {
return [part, <div>spacer</div>];
});
// Remove the last spacer
result.pop();
return (
<div>
{result}
</div>
);
}
});
The accepted answer is 5 years old. For this problem issue #3368 was created and based on the solution provided by a Facebook employee working on React, react-string-replace was created.
Using react-string-replace, here is how you can solve your problem
const reactStringReplace = require('react-string-replace');
const HighlightNumbers = React.createClass({
render() {
const content = 'Hey my number is 555:555:5555.';
return (
<span>
{reactStringReplace(content, ':', (match, i) => (
<div className="spacer"></div>
))}
</span>
);
},
});
As I am a perfectionist. I think this pattern is perfect:
String.prototype.replaceJSX = (find, replace) => {
return this.split(find).flatMap((item) => [item, replace]);
}
Usage:
variable.replaceJSX(":", <br />);