I have a string I need to parameterise like 'Hello {name}, how are you?'. I want to replace the curly braces and text inside with a variable then render it in my React Component but I also need that text to be highlighted and bold by wrapping the variable text in a span/strong tag e.g. of desired final result
Hello <span class="text-info"><strong>Dave</strong></span>, how are you?
I'm using React/JSX and I know how to replace the curly braces and text inside them using String.replace then render it e.g.
// This string with the placeholder curly braces would be received from an API call to a server. Only set here for demonstrative purposes
let string = 'Hello {name}, how are you?'
let name = 'Dave' // Likewise would not be set manually here, it's held in a redux store
let greeting = string.replace(/{(.*?)}/, name);
// This renders the greeting as you'd expect e.g. <p>Hello Dave, how are you?</p>
return (
<p>{greeting}</p>
)
However, if I try and replace the curly braces with a span element it renders incorrectly with [object Object] instead of my parameter
// ...rest of stateless Component.jsx
let greeting = string.replace(/{(.*?)}/, <span>{name}</span>);
// This renders the HTML <p>Hello [object Object], how are you?</p>
return (
<p>{greeting}</p>
)
I think it must be something to do with React escaping something but to be honest that's a total guess. Any ideas how I can achieve the desired functionality?
<span>{name}</span>,will be replaced with the result ofReact.createElement("span", null,{name})which returns an object, that's why your resulting string is showing as[object Object]. - slugo"<span>" + {name} + "</span>"for example, and then render using setInnerHtml. But there probably are other ways. - slugo