1

I was following the 'Add React to a Website' guide on https://reactjs.org/docs/add-react-to-a-website.html#optional-try-react-with-jsx but it does not seem to work correctly for some reason.

The code that does not work:

index.html:

    <html>
    <head>

    <!-- Load React -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <!-- Load React component. -->
    <script src="test.js"></script>

    </head>

    <body>

    <div id="root"></div>

    </body>

    </html>

test.js:

    ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
    );

The code above will produce a blank page but when I add the react code on the index.html page like this:

   <script>
    ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
    );
   </script>

It does work.

I have tried to replace

    <script src="test.js"></script>

with

    <script src="/test.js"></script>

and

    <script src="./test.js"></script>

but that still does not work.

Also when I inspect element on the blank page it does show that it loads test.js

Can someone please tell me what I am doing wrong?

5
  • Quick fix: move <script src="test.js"></script> to below <div id="root"></div>. Let me know if you want a full answer. Commented Sep 8, 2018 at 20:46
  • 1
    It still does not work I have done as you told me. Commented Sep 8, 2018 at 20:50
  • Ah, I see what's happening. Basically, follow the guide you linked to more carefully. You need <script src="test.js" type="text/babel"></script>. Commented Sep 8, 2018 at 20:58
  • Aha ok thank you it works now! Commented Sep 8, 2018 at 21:01
  • I've written an answer so that an answer can be accepted for this question. For what it's worth, I recommend create-react-app if you want to get started with React. Commented Sep 8, 2018 at 21:07

2 Answers 2

1

As the guide says:

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it.

So you need <script src="test.js" type="text/babel"></script>.

Sign up to request clarification or add additional context in comments.

Comments

1

Even you can do it without adding text/babel by just using React.creatElement API as recommneded by Dan Abramov, author of redux and part of Reactjs core team.

Here is the working codesanbox: React with no build config

2 Comments

Sure, it works without JSX. But nobody wants to write React without JSX...
Yeah this is for just understanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.