3

I am using react.js without node.js, and I want to link multiple script files in my html file but i can't.

Basically, this is my code:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" type="image/png" href="src/reactFavicon.png">
    <link href="https://fonts.googleapis.com/css?family=Ma+Shan+Zheng|Righteous&display=swap" rel="stylesheet">
    <title>Users</title>
    <script type="application/javascript" src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script type="application/javascript" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script type="application/javascript" src="https://unpkg.com/[email protected]/babel.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">
        const rootElement = document.getElementById('root')

        class Users extends React.Component {
            constructor(props) {
                super(props)
                this.state = {
                    items:[],
                    isLoaded: false
                }
            }

            componentDidMount() {
                fetch('https://jsonplaceholder.typicode.com/users')
                .then(res => res.json())
                .then(json => {
                    this.setState({
                    isLoaded: true,
                    items: json
                })
                })
            }

            render() {
                const title = this.props.title;
                var {isLoaded, items} = this.state;
                if(!isLoaded) {
                    return <div>Loading...</div>
                } else {
                    return(
                        <div class="Users">
                            {title}
                            <ul>
                                {items.map(item => (
                                    <li key={item.id}>
                                        {item.name} | {item.email} ||| lives in {item.address.street}, {item.address.suite} ({item.address.city}), his/her phone number is {item.phone} and works in <strong>{item.company.name}</strong>.
                                    </li>
                                )) }
                            </ul>
                        </div>
                    )
                }
            }
        }



        function App() {
            return (
                <div>
                <Users 
                    title = "Users"
                />
                </div>
            )
        }

        ReactDOM.render(
            <App />,
            rootElement
        )
    </script>
</body>
</html>

And I want to separate the script file (text/babel) to a separate file and link it to the html, but that doesn't work despite VS Code not showing any error, I don't know what to do, I can't use Node (they don't use it in my work, nothing I can do).

This is the code that doesn't work:

<body>
    <div id="root"></div>
    <script type="text/babel" src="users.js"></script>
<body>

You can also use this example:

https://dev.to/luispa/lets-try-react-without-nodejs-3a7

Just like that, but with the script separated and linked/referenced in the html file, please help me...

1 Answer 1

1

You need to input the correct relative path to the js file within the index.html file:

<body>
    <div id="root"></div>
    <script type="text/babel" src="./path/to/users.js"></script>
<body>

On a side note, I'd recommend compiling the babel code, so that it doesn't have to be transpiled on the client (for EVERY user). Better yet, simply use webpack to create different compiled bundles.

Here's a working example of some compiled & minified JS (babel to es5 JS):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Ma+Shan+Zheng|Righteous&display=swap" rel="stylesheet">
    <title>Users</title>
    <script type="application/javascript" src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script type="application/javascript" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="application/javascript">
        "use strict";function _instanceof(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!_instanceof(e,t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _possibleConstructorReturn(e,t){return!t||"object"!==_typeof(t)&&"function"!=typeof t?_assertThisInitialized(e):t}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var App=function(e){function t(){var e,n;_classCallCheck(this,t);for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];return _defineProperty(_assertThisInitialized(n=_possibleConstructorReturn(this,(e=_getPrototypeOf(t)).call.apply(e,[this].concat(o)))),"state",{items:[],isLoaded:!1}),_defineProperty(_assertThisInitialized(n),"render",function(){return n.state.isLoaded?React.createElement("div",{style:{textAlign:"left",padding:20}},React.createElement("h1",{style:{textAlign:"center"}},"Users"),React.createElement("ul",null,n.state.items.map(function(e){return React.createElement("li",{key:e.id},e.name," | ",e.email," ||| lives in ",e.address.street,","," ",e.address.suite," (",e.address.city,"), his/her phone number is ",e.phone," and works in ",React.createElement("strong",null,e.company.name),".")}))):React.createElement("div",{style:{textAlign:"center"}},"Loading...")}),n}return _inherits(t,React.Component),_createClass(t,[{key:"componentDidMount",value:function(){var e=this;fetch("https://jsonplaceholder.typicode.com/users").then(function(e){return e.json()}).then(function(t){e.setState({isLoaded:!0,items:t})})}}]),t}();ReactDOM.render(React.createElement(App,null),document.getElementById("root"));
    </script>
</body>
</html>


Working standalone repo:

https://github.com/mattcarlotta/standalone-example

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

2 Comments

index and js are on the same folder, the path is correct.
Updated answer to include standalone repo. It doesn't matter if it's in the same folder, it still needs to be relative: ./users.js or ./todos.js.

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.