I'm trying to replace parts of a string with JSX tags, like so:
render: function() { result = this.props.text.replace(":",<div className="spacer"></div>); return ( <div> {result} <div> ); }
But given that this.props.text
is Lorem : ipsum
, it results in
<div> Lorem [object Object] ipsum. </div>
Is there a way to solve this or another way to replace parts of a string with JSX tags?
To add script tag or code in head tag <head> , use react-helmet package.
You use ${} in string templates like const k = `my name is ${name}` you use {} whenever you want to put some Java code in your JSX code like <div attr={name}>{name}</div>
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> ); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With