Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of string with tag in JSX

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?

like image 365
Magnus Engdal Avatar asked May 27 '15 06:05

Magnus Engdal


People also ask

Can we use script tag in JSX?

To add script tag or code in head tag <head> , use react-helmet package.

What is ${} in JSX?

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>


1 Answers

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>     );   } }); 
like image 145
Anders Ekdahl Avatar answered Sep 19 '22 22:09

Anders Ekdahl