Cellydy
Cellydy

Reputation: 1339

Client Side React.js

I'm trying to get React.js to work client side on my LAMP stack web application. I want to implement the following slider on my website: https://github.com/airbnb/rheostat. I have managed to get react.js to work using the following guide: https://gist.github.com/jineshshah36/4a0326abb191781184e9.

The following code works:

<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel">
    var HelloComponent = React.createClass({
        render: function() {
            return (
                <h1>Hello, World!</h1>
            )
        }
    })
    ReactDOM.render(<HelloComponent />, document.querySelector('#app'))
</script>

I tried to use the rheostat slider by changing the above to the following.

<div id="slider-root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://raw.githubusercontent.com/airbnb/rheostat/master/src/Slider.jsx"></script>
<link href="https://raw.githubusercontent.com/airbnb/rheostat/master/css/slider.css" rel="stylesheet" type="text/css">
<script type="text/babel">
    import Rheostat from 'rheostat';
    ReactDOM.render(<Rheostat />, document.getElementById('slider-root'));
</script>

Am I importing the files wrong? Do I need to process the jsx file before it can be executed by the browser? If yes, how do I do that?

Upvotes: 1

Views: 1090

Answers (1)

John Weisz
John Weisz

Reputation: 31924

Do I need to process the jsx file before it can be executed by the browser?

Yes, precisely. jsx is essentially a syntax extension primarily for working with React, and you will need to compile/transpile first. If you don't want to do that, you can simply leave jsx out altogether and just use:

ReactDOM.render(React.createElement(Rheostat), document.getElementById('slider-root'));

If you are interested in jsx, consider the following:

<div>
    <span>Text here</span>
</div>

This is not valid JavaScript, the browser will barf up all sorts of syntax errors restlessly. This code first has to be compiled, or transpiled into valid JavaScript. When using React, the above is to be compiled into:

React.createElement(
    "div",
    null,
    React.createElement(
        "span",
        null,
        "Text here"
    )
);

One of the most common tools for this is Babel. TypeScript also has built-in support for typed jsx, dubbed tsx.

Upvotes: 1

Related Questions