I have a string with a variable inside:
var template = '<div>Hello {username}</div>';
The username is set by the state, how to parse this string and turn it into a react component?
Use RegExp
to identify all {}
sets. Then, replace the value with the state value and update the string. Finally use dangerouslysetinnerhtml
to insert the HTML string into react node. See the example.
Hope this helps!
class App extends React.Component{
constructor(props) {
super(props)
this.state = {
username: 'Pranesh',
userId: 124,
}
}
render(){
var template = '<div>Hello {username}. Your user id is {userId}.</div>';
var r = template.match(/\{[\w]+\}/g);
r && r.forEach((state) => {
var regex = new RegExp(state, 'g')
var stateItem = state.split(/{|}/g)[1]
template = template.replace(regex, this.state[stateItem])
})
return <div dangerouslySetInnerHTML={{__html: template}}/>
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With