1

I'm new to react, and I am having trouble with multiple components.

This is the error I get Uncaught ReferenceError: require is not defined

Code that I'm using.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
    <script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xtf1/t39.3284-6/11057100_835863049837306_1087123501_n.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app"></div>
    <script type="text/babel" src="js/layout.js"></script>
</body> 
</html>

layout.js

import React from "react";
import ReactDOM from "react-dom";

import Header from "./header";

class Layout extends React.Component {
    render() {
       return(
        <div>
           <Header/>
        </div>
    );
    }
}

const app = document.getElementById("app");
ReactDOM.render(<Layout/>, app);

And header.js

import React from "react";
import ReactDOM from "react-dom";

export default class Header extends React.Component {
    render() {
        return(
            <h1>Hello header</h1>
    );
    }
}

1 Answer 1

3

Babel handles only the transpilation part (i.e. converts es2015 and jsx syntax into valid ES5). But you still need to use either a bundler (webpack, browserify) or a module loader (systemjs or jspm) to load modules.

Here is an example using SystemJS. Example.

Configure systemjs loader to load libs from cdn

System.config({
    transpiler: 'babel',
    baseURL: '',
    map: {
      babel: 'https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js',
      react: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js',
      'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js'
    }
});

// load application
System.import('script.js');

Import local files

// inside script.js
import React from "react";
import ReactDOM from "react-dom";
import Header from "./header.js"; //note extension

class Layout extends React.Component {
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! Working nicely :)

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.