I am currently working on some code that gets the text (from the cms) in a textblock and replaces so called 'dynamic words' that are defined in the CMS, so when you click a 'dynamic word' it gives you an alert. I now have this code but it doesn't work and it did work with hardcoded text instead of dynamic words from the CMS. Can anyone see where the problem is here?
For extra info leave an message ( For example if you need to know what an specified console.log gives back :) )
import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';
export const ArticleBodyText = ({ item, dynamic_words }) => {
useEffect(() => {
const el = document.getElementById('this-text');
const text = el.innerHTML;
dynamic_words.map(word => {
const dynamic_word = word.word?.[0].text;
const newText = text.replace(
`/\b${dynamic_word}\b/g`,
`<span class='dynamic-word'>${dynamic_word}</span>`
);
el.innerHTML = newText;
const spans = el.querySelectorAll('.dynamic-word');
for (let i = 0; i < spans.length; i += 1) {
spans[i].addEventListener(
'click',
function () {
if (this.innerHTML === dynamic_word) {
alert('You clicked a dynamic word!');
}
},
false
);
}
});
});
return item?.primary?.body_text.map(bodytext => (
<TextBlock
id="this-text"
key={bodytext.text}
dangerouslySetInnerHTML={{ __html: bodytext.text }}
/>
));
};
EDIT: Working version:
import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';
export const ArticleBodyText = ({ item, dynamic_words }) => {
useEffect(() => {
const el = document.getElementById('this-text');
const text = el.innerHTML;
const newText = text.replace(/\bte\b/g, "<span class='dynamic-word'>te</span>");
el.innerHTML = newText;
const spans = el.querySelectorAll('.dynamic-word');
for (let i = 0; i < spans.length; i += 1) {
spans[i].addEventListener(
'click',
function () {
if (this.innerHTML === 'te') {
alert('Je hebt op een dynamic word geklikt!');
}
},
false
);
}
});
return item?.primary?.body_text.map(bodytext => (
<TextBlock
id="this-text"
key={bodytext.text}
dangerouslySetInnerHTML={{ __html: bodytext.text }}
/>
));
};
const newText = text.replace(/\bte\b/g, but how can i replace 'te' with the dynamic_word const?"<span class='dynamic-word'>te</span>"?/\b${word}\b/g; This newText has to be inside template literals