javascripthtmlreactjstemplate-literals

React ${} string replacer doesn't work


I'm learning React using a textbook and the string replacer ${} from this particular example doesn't work and can't figure out why. I've double checked any typos to make sure. Other examples from the book has worked fine so far.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class Hello extends React.Component {
        constructor (props) {
          super(props)
          this.clickHandler = this.clickHandler.bind(this) //isolates 'this' of Hello class from other 'this'
        }
        clickHandler (e) {
          const name = this.props.name
          window.alert('Hello, ${name}') //!!this doesn't work....
        }
        render () {
          return (
            <div onClick={this.clickHandler}>Say Hello</div>
          )
        }
      }
      ReactDOM.render((<Hello name="Johnny" />),document.getElementById("root"))
    </script>
  </body>
</html>

Solution

  • use back-tick

    window.alert(`Hello, ${name}`)