Set attribute for custom DOM nodes in text preview component

I want to add the / setAttribute class for custom DOM nodes when writing text in a custom text editor bbcode. When innerHTMLof is <item></item>not empty, I filter the array itemsto find the value that matches. There can be an unlimited number of nodes item. (i.e. 2, 5, 10)

Therefore, whenever I click the icon with the name item, it appears in textarea as [item][/item]well as in the preview component as <item></item>. Once the element is written, let's say [item]id123[/item]I have it in the DOM <item>itemName123</item>.

Now I'm doing DOM manipulation outside of React with:

const setAttributes = (el, item) =>{
    el.dataset.img = item.img;
    el.setAttribute('class', _.toLower(item.color))
  };

const updateItems = () =>{
    if(document.querySelectorAll('item')) {
      document.querySelectorAll('item').forEach(el => items.find(item => {
        if(_.toLower(el.innerHTML) === _.toLower(item.id))
          setAttributes(el, item)
      }));
    }
 }

, , , , , .

/ , dangerouslySetInnerHTML, , includes map, filter , ES6, .

, , -, .

: , setAttributes() && updateItems() .

# 2: , [item][/item], regexp text.replace(/\[item]/g, <item>).replace(/\[\/item]/g, </item>), , - regexp setAtrribute ? ,

new RegExp(/\[item]/+ _.toLower(item.name)+ /\[\/item]/, 'g');

text.replace(<item class="${item.quality}">${_.toLower(item.name)}</item>)

.

!

+4
1

. RegExp + pattern.exec(text) while . for(let..of) .

0

Source: https://habr.com/ru/post/1685626/


All Articles