Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

jsx

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?

like image 416
chulian Avatar asked Feb 05 '23 20:02

chulian


1 Answers

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>
like image 100
Pranesh Ravi Avatar answered Feb 09 '23 02:02

Pranesh Ravi