Using HTML placeholders in React

424 views Asked by At

I grab content from a CMS via Gatsby. Inside the markup there are placeholders which should be replaced with React elements.

So I get sth like this:

let content = '<span>Hello World [placeholder]!</span>';

and in React I want to change it to sth like this (where the markup for the tooltip comes from a React element):

let content = '<span>Hello World <div class="tooltip">Important warning</div>!</span>';

The final html with the replaced elements should be dumped into the DOM using dangerouslySetInnerHTML.

I tried using react-string-replace:

reactStringReplace(content, '[placeholder]', () => (<Tooltip />));

but it gives me an array containing a mix of strings and React elements that can't be concacenated without breaking the HTML structure.

What would be a good approach to tackle this issue? Or am I wrong using placeholders in the CMS altogether?

1

There are 1 answers

0
nerdess On BEST ANSWER

i found a really good npm package that provides this functionality and much more: https://interweave.dev/