Home > Blockchain >  Use JSX when using react loaded by <script> tag on html page
Use JSX when using react loaded by <script> tag on html page

Time:02-02

Is this possible to use JSX attributes, without bundler? (just using a HTML which is loading react in tag)

index.html file:

<html lang="en">
  <body>
    <div id="root"></div>

    <script src="react.development.js" crossorigin></script>
    <script src="react-dom.development.js" crossorigin></script>

    <script src="index.js"></script>
  </body>
</html>

index.js file:

class App extends React.Component {
  render() {
    return <div>Content</div>;
  }
}

const e = React.createElement;
const domContainer = document.querySelector("#root");
ReactDOM.render(e(App), domContainer);

CodePudding user response:

You need a transpiler, not a bundler. You can run one client-side, but shouldn't because it introduces performance problems (and can make it harder to debug your code).

This is covered in the documentation:

The quickest way to try JSX in your project is to add this <script> tag to your page:

 <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it. Here is an example HTML file with JSX that you can download and play with.

This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production. When you’re ready to move forward, remove this new <script> tag and the type="text/babel" attributes you’ve added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script> tags automatically.

  •  Tags:  
  • Related