Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11285

How do I get JSX supported in my application?

I have the following in my index.js file

class PersonProfileBadge extends React.Component {
    constructor(props) {
        super(props);
        this.alias = this.props.alias;
    }

    render() {
        return e(
            'img',
            {
                src: `https://internal-cdn.foo.com/somepath/?uid=${this.alias}`,
                className: 'profile_photo'
            }
        );
    }
}

and it works when I render it like so

ReactDOM.render(
    e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
    navProfilePicture
);

But I'm trying to get JSX support since it makes the code look generally much more readable

ReactDOM.render(
  <PersonProfileBadge alias='stupidfatcat' />,
  navProfilePicture
);

But I'm getting this error:

Uncaught SyntaxError: Unexpected token '<'

In my index.html I have the following imports

<script src="internalcdnpathto/static/react/react.production.min.js"></script>
<script src="internalcdnpathto/static/react-dom/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="/static/index.js"></script>

Not entirely sure what I'm doing wrong or where to even get started.

Upvotes: 0

Views: 104

Answers (2)

msalla
msalla

Reputation: 765

You generally want to add a preprocessor in order to use JSX. The quickest way to try JSX in your project is to add this tag to your page:

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

Now you can use JSX in any tag by adding type="text/babel" attribute to it. This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production.

Read more in the official React docs.

Upvotes: 1

Gabriel Nadaleti
Gabriel Nadaleti

Reputation: 1646

You need babel to compile your code from JSX to javascript from this:

ReactDOM.render(
  <PersonProfileBadge alias='stupidfatcat' />,
  navProfilePicture
);

to that:

ReactDOM.render(
  e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
  navProfilePicture
);

You should utilize a bundler like webpack so you parse your code everytime you change something, i'd suggest creating a project via create-react-app

or take a look at Babel Standalone

Upvotes: 0

Related Questions