-4

I have a class App that extends React.Component, in App there is the following render() code

 render() {return(
  <div style={styles}>
  <button type="submit" value="Go" onClick=" alert('Hi') ">Go</button>
  </div>
  )}

replacing the quotations with curly brackets make the code work

<button type="submit" value="Go" onClick={ alert('Hi') }>Go</button>

I know that in React we should use { } if we want to add JavaScript code, but in this case we already can write HTML like this onClick=" alert('Hi') " so why this is not working?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
E.S
  • 101
  • 1
  • 1
  • 9
  • 1
    What do you mean *"we already can write HTML like this"*? Sure you can write it, it's valid syntactically, but then the attribute is just the *string*. – jonrsharpe Jun 20 '19 at 15:16

1 Answers1

3

Passing javascript as a string is not recommended for security / optimization issues. Also, the development experience is better when the IDE knows how to differentiate between regular strings and JS code.

For those reasons, React does not allow you to use it like that.

Also, remember, JSX is not HTML. It is XML built for React, so not all HTML tags, attributes and nesting work in JSX and vice-versa.

Danilo Fuchs
  • 911
  • 8
  • 17