1

I am trying to implement a wrapper API file for a ReactJS component.

For example, /js/test.react.js

   /** @jsx React.DOM */
var TESTCLASS = React.createClass({
    render : function() {
        return (
            <div> Test </div>
        );
    }
});

I have written a wrapper JavaScript file for that:

var testClass = {
    load: function () {
        var script = document.createElement("script");
        script.type = "text/jsx";
        document.head.appendChild(script);
        script.onload = function(){
            React.render(
                <TESTCLASS/>,
                document.body)
        };
        script.src ="./js/test.react.js";
    }
};

Then I can use the wrapper API JavaScript in a third-party HTML.

<html>
<head>
    <title>Hello React</title>
    <script src="http://fb.me/react-0.12.2.js"></script>
    <script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script type="text/jsx" src="test.js"></script>
</head>
<body>

<div id="content"></div>
<script>
    testClass.load();
</script>

</body>
</html>

However, it seems to me /js/test.react.js cannot be dynamically loaded as pure JavaScript file. Can any expert explain to me the reason and provide a proper solution to write my wrapper API JavaScript file?

1
  • Cant you just compile into jsx every time? A grunt-task can do that automatically upon every code change. Commented Jan 15, 2015 at 11:44

1 Answer 1

3

JSXTransformer*.js exports a global JSXTransformer object which has an exec() function, which transpiles JSX then eval()s the result.

You could try running JSXTransformer.exec() with the script's contents onload first.

Also, FYI, the @jsx pragma is no longer required as of React 0.12 :)

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

1 Comment

JSXTransformer has been deprecated reactjs.org/blog/2015/06/12/…

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.