I just a wrote function helper to replace some Texts, Components, and even HTMLs to a template string for my project. It turned out so nice and smooth.
const replaceJSX = (str, replacement) => {
const result = [];
const keys = Object.keys(replacement);
const getRegExp = () => {
const regexp = [];
keys.forEach((key) => regexp.push(`{${key}}`));
return new RegExp(regexp.join('|'));
};
str.split(getRegExp()).forEach((item, i) => {
result.push(item, replacement[keys[i]]);
});
return result;
};
Usage:
const User = ({ href, name }) => {
return (
<a href={href} title={name}>
{name}
</a>
);
};
const string = 'Hello {component}, {html}, {string}';
return (
<div>
{replaceJSX(string, {
component: (
<User
href='https://stackoverflow.com/users/64730/magnus-engdal'
name='Magnus Engdal'
/>
),
html: (
<span style={{ fontWeight: 'bold' }}>
This would be your solution
</span>
),
string: 'Enjoy!',
})}
</div>
)
And you'll get something like this:
<div>Hello <a href="https://stackoverflow.com/users/64730/magnus-engdal" title="Magnus Engdal">Magnus Engdal</a>, <span style="font-weight: bold;">This would be your solution.</span>, Enjoy!.</div>