Kiran Dash
Kiran Dash

Reputation: 4956

Reactjs with JSX: Unexpected token '<'

I am a beginner in react. When I render elements with createElement, it works fine. But rendering like below with JSX, it throws and error saying Uncaught SyntaxError: Unexpected token <

const { createElement } = React;
const { render } = ReactDOM; 

const style = {
    fontFamily: 'Arial',
    color: 'White',
    backgroundColor: 'Red',
    padding: '10px',
    border: '10px solid black'
}

render(
    <h1 id="emp-title" className="header" style={style}>Full time Employee</h1>,
    document.getElementById('react-container-jsx')
);
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
        <title>React 101</title>
    </head>
    <body>
        <div id="react-container-jsx"></div>
        <script src="index.js"></script>
    </body>
</html>

Attempts: tried but did not work

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

Also

<script src="index.js" type = "text/jsx"></script>

Didn't work. Any help is much appreciated.

Upvotes: 0

Views: 186

Answers (1)

Prithwee Das
Prithwee Das

Reputation: 5226

You will need to link babel-standalone as well

And add type="text/babel" to the script tag.

Working snippet:

const { createElement } = React;
const { render } = ReactDOM; 

const style = {
    fontFamily: 'Arial',
    color: 'White',
    backgroundColor: 'Red',
    padding: '10px',
    border: '10px solid black'
}

render(
    <h1 id="emp-title" className="header" style={style}>Full time Employee</h1>,
    document.getElementById('react-container-jsx')
);
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
        <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
        <title>React 101</title>
    </head>
    <body>
        <div id="react-container-jsx"></div>
        <script src="index.js" type="text/babel"></script>
    </body>
</html>

Upvotes: 2

Related Questions