4

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?

chulian
  • 3,767
  • 4
  • 21
  • 23
  • 2
    Is there any reason you aren't just using jsx instead of a string? `var template =
    Hello {username}
    ` works right out of the box without anything fancy
    – finalfreq Oct 24 '16 at 01:20
  • I have the HTML in separate files, work policy, designers are not allowed to change js files, just HTML files – chulian Oct 24 '16 at 04:41
  • 1
    the question was already asked and [answered](http://stackoverflow.com/a/33342686/7049654) – Konstantin Vitkovsky Oct 24 '16 at 05:21
  • I'm using babel.transform('
    hello
    ').code but get an error 'Unexpected token', also "import babel from 'babel-core';" generates an error "TypeError: isNaN is not a function", looks like it doesn't play nice with my meteor + redux +react app
    – chulian Oct 24 '16 at 23:44

2 Answers2

8

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>
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
0

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

Lionel Dcosta
  • 177
  • 1
  • 2
  • 13