L Zh L Zh - 1 month ago 15
React JSX Question

Hello-world in reactjs installation guide not working

I am completely new to React.js, and started to learn from the tutorial page.

MacOSX Sierra v10.12

In the terminal, I did:

npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start


Then, I modified App.js to be:

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

ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);


After saving App.js, nothing shows up on the page.
Screenshot

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<!--
Notice the use of in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
<script type="text/javascript" src="/static/js/bundle.js"></script></body>
</html>


Not sure what went wrong. Please help. Thanks!

Answer

Here is where you went wrong: App.js is expected to be a React component, index.js is the file that actually handles rendering to the dom. Here is the original index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

it is importing App as a component and attempting to render it. You basically made a copy of index.js in App.js which breaks everything since index.js is what actually handles the initial DOM rendering.

ou have two options:

change App.js to this:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return <h1>Hello, world!</h1>
  }
}

export default App;

or in the index.js copy and paste the code you wrote previously.