简体   繁体   中英

React Components Not Rendering

I can't even get my root app component to render. I load localhost and it loads index.html successfully with no js errors but nothing is rendered to the page. I can't pinpoint the problem if there are no errors :). I looked at my code and I don't know what the deal is. I'm new to React so...could be a bunch of issues below, I don't know.

server.js

var express = require('express'),
    app = express();

app.set("view options", {layout: false});
app.use(express.static('.'));
app.set('views', __dirname + '/');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.get('/', function (req, res) {
    res.render('index.html');
});

app.listen(4000, function () {
    console.log('Example app listening on port 4000!');
});

index.html

<!DOCTYPE html>
<html lang="en">
    <head></head>
    <body>
        <div class="ink-grid vertical-space">
            <div id="content">
                <div class="panel vertical-space">
                    <div id="app"/>
                </div>
            </div>
        </div>
        <script type="text/babel" src="index.js"></script>
    </body>
</html>

index.js

import React from 'react';
import { render } from 'react-dom';

import App from 'src/components/App';

const app = document.getElementById('app');
render(<App/>, app);

App.js

import React, { Component } from 'react';
import CompanyList from 'src/components/CompanyList';

class App extends Component {
    render() {
        return (
            <div id="companyList">
                <CompanyList />
            </div>
        );
    }
}

export default App

CompanyList.js

import React, { Component } from 'react';

class CompanyList extends Component{
    render(){
        return (
            <h3>No Companies Found</h3>
        );
    }
}
export default CompanyList

It doesn't work because of the type="text/babel" on you're script tag. This type was intended to use with the now deprecated babel browser to transpile ES6 and JSX in the browser.

You have to change the type to "text/javascript" to run the file. However, as the browser doesn't understand JSX, and some parts of ES6, this will mainly throw errors.

What you'll have to do in addition to make it work, is to use a build system, such as webpack, to transpile ES6 and JSX using babel, and bundle you're files, to something the browser can use. Try this guide .

If you just want to practice react without the hassle of a build system, you can use the React Base Fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM