I have this code on CodePen: https://codepen.io/anon/pen/OdOyJX that works perfectly, and I am confused about why this works.
ReactDOM.render(
<div>Hello, world!</div>,
document.getElementById('root')
);
In the JavaScript settings, there is no preprocessor selected, so I expect the JSX syntax to fail as "<" is an invalid token. What makes this work on CodePen?
If you really want to use CodePen, you need to add react as a JS dependency. Click on “Settings” at the top of your pen, then “Javascript” in the pop-up. Under “javascript preprocessor”, select Babel, and under “add external scripts/pens”, type “react”. Select both react and react-dom .
In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a JavaScript engine will parse.
You can import React (any pretty much any other npm package) from Skypack like this: import React from "https://cdn.skypack.dev/[email protected]"; CodePen will help you fix imports like that automatically. You'll see an icon like this come up, which you click to open and are offered a button to click to fix the issue.
If you look at your Pen now, it looks like it does indeed fail on the <
in your JavaScript, but if you turn Babel on, it works well.
Babel must have been accidentally turned on my default back when you asked this question!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With