1

i'm new in react.js, i used CDN links to compile some simple react.js code into my html, but i get this error:

"Uncaught SyntaxError: Unexpected token <"

then i searched and i saw somebody said that i should add:

type="text/babel" or type="text/jsx"

to my script tag, i did, but after that, my html didn't know my .js file!

this is my html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="fa">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title> title </title>
</head>

<body> 

  <div id="app"> </div>

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

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>

  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"</script>

  <script type="text/babel" src="myreact.js"> </script>

</body>
</html>

and this is my react.js file:

'use strict';

class MyComponent extends React.Component{ 
    render()
    {
      return  "hello";
    }
}

ReactDOM.render(
  <MyComponent/> , document.getElementById('app')
);

please help me to code in react.js.

2

1 Answer 1

2

If you are using CDN, first two you need are to render React into a DOM and the third one (babel) enables JSX and ES6. I have reordered the imports, have included cdn for babel after importing react and react-dom.

<!DOCTYPE html>
<html lang="en">
<body>
  <div id="app"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script type="text/babel">
    'use strict'
    class Application extends React.Component {
     render() {
      return(
          <div>React App</div>
      );
     }
    }

    ReactDOM.render(<Application />, document.getElementById('app'));
  </script>
</body>
</html>

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

5 Comments

thanks, it works when i put my react.js code in my html file with <script> tag, but i want to have separate .js file and make a link to this .js file from my html. can i do this? do you have any idea?
Yes, you can, what is your directory structure? Where is your js located?
my .js file and my .html file are in the same folder. react\file.html and react\file.js. what should i do?
Change this <script type="text/babel" src="myreact.js"> </script> to <script type="text/babel" src="./myreact.js"> </script>
And if my answer was helpful, please accept it :) Thanks in advance :)

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.