3 ms·
JSX/createElement is not just syntax sugar though. It avoids the whole step of parsing the template. Because JSX is JS code, you can pass native JS values to it
by raquo 11y ago
JSX/createElement is not just syntax sugar though. It avoids the whole step of parsing the template. Because JSX is JS code, you can pass native JS values to it including callbacks. Whereas anything you could pass to mustache-style templates will be stringified.
So for example in case of parsed templates, to pass a callback to onClick you'd need to define a convention on how you're going to locate the callback by a given string (since you can't pass the function itself, you need to pass some "name" of that function). Whatever logic that will be, the result will not feel like React anymore because you're back to typical framework-specific template magic instead of using plain JS.
- nailer 11y ago> to pass a callback to onClick Putting behaviour in HTML is a bad idea. Leave it in JS, and have one place to go when the behaviour changes.
- raquo 11y ago> Putting behaviour in HTML is a bad idea This is not what I'm doing. JSX is JS. I'm not putting any logic "in HTML". If I were able to express what I'm doing in mustache-style syntax, it would be: Blah blah <a onclick="{{ callback }}">Click me</a> Blah Where `callback` is a reference to a JS function (rather than a string holding it's name). What's your ideal way of registering an onclick callback?
- nailer 11y agoThe moustache you're demonstrating there has the same problem. Add event listeners in JavaScript, not in moustache / jsx / whatever.
- raquo 11y agoSo, once again, JSX is JS. You're free to write the exact same thing without XML syntax. If you don't like that either, then what you're really saying is "Don't generate HTML using JS". Why not? The benefits are obvious: * With React & ESLint you get basic checks to make sure you're not passing non-existent variables * Your IDE understands what you're doing and lets you jump to callback definitions * You understand what you're doing because you have one obvious place where you do templating and data binding. * Your actual behaviour logic is still separated from your template, living in some other JS file. On the other hand, if you add event listeners to HTML from JS the classic way, you get other problems: * You're querying the DOM tree by CSS classes or some custom attributes. It's surely a familiar way of doing things, but also fragile and unintuitive. * It requires your JS to know the structure of your DOM to some extent, and that structure is defined elsewhere. So it's basically the same problem as with mustache templates – passing around magic strings – but the other way around. * Neither ESLint nor IDE will help you do it.