chulian
chulian

Reputation: 4117

How to parse a string with variables into a react component?

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?

Upvotes: 4

Views: 16762

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19113

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>

Upvotes: 8

Lionel Dcosta
Lionel Dcosta

Reputation: 176

I am not sure what you are trying to do but you can do var template = (<div>{this.state.username}</div>)

Upvotes: 0

Related Questions