ExoticChimp ExoticChimp - 1 year ago 142
React JSX Question

Replace Curly Braces in string with a HTML span Node in JSX

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 (

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 (

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?

JSFiddle: https://jsfiddle.net/ExoticChimp1990/o69ymt7q/

Answer Source

You can try replacing by a string containing raw html tags and then render your div using dangerouslySetInnerHTML.

var greeting = textToEnhance.replace(/{(.*?)}/, '<span>'+this.props.name+'</span>'); 

return <div dangerouslySetInnerHTML={{__html:greeting}}></div>;