Good day. I use React JS. Render component. I have a dynamic line:

var string = "#k - #score - #date": 

We do not know the exact order. And suppose that there are a very large number of such "tags" in the line.

We have an object with the keys of these labels and the jsx pattern corresponding to the label.

 var template = { "#k" : <div>Комадна</div>, "#score" : <span>Результат</span> }; 

The size of this object is always equal to the number of tags in the line above.

so here The render should return a jsx pattern based on this string. How to implement it?

thank

  • And you see what JSX is transformed into, perhaps it’s easier for you to form a result right away than to go that roundabout way. - D-side

1 answer 1

Work example:

 class Example extends React.Component { templates = { "#k" : <span>Комадна</span>, "#score" : <span>Результат</span> }; renderText = (text, regExp, fn) => { const parts = text.split(regExp); for (let index = 1; index < parts.length; index += 2) { parts[index] = fn(parts[index], index); } return parts; }; matchValue (match) { if (match === '') { return match; } if (this.templates.hasOwnProperty(match)) { return this.templates[match]; } return match; } renderNextLine (text) { if (!text) { return null; } return this.renderText(text, /(#[a-zA-Z]+)/g, this.matchValue.bind(this)) } render () { const string = "#k - #score - #date"; return <div> {this.renderNextLine(string)} </div> } } 

Decryption: We need to parse the resulting string in a regular way so that we get a structured array, where certain elements of this array will be the key to our “pattern”.

Parse the code on a regular basis (#[a-zA-Z]+) , and we get such a set. Next, we apply to each odd element our render template in which we are looking for a match with a set of templates . And finally substitute.

I used this approach for draft-js , when I did a custom render of certain things.

  • In this example, we will lose all spaces and other characters without the #. - devn
  • For example. The string "#k - #score - #date" Returns <div> Komadna </ div> <span> Result </ span>, and the remaining characters will be lost - devn
  • Hmm, well, yes, I did not understand from the beginning that you want to make the usual replacement on some "template-names". I did the same, if I make an example, I'll - Vasily Barbashev
  • @devn check, must meet your requirements) - Vasily Barbashev
  • Super thanks)) - devn