I am new in React.js development and I tried a simple hello world page but I got an empty page and also I didn't get any error.
I use create-react-app
for creating this project. After creating the project,I started the localhost with npm
command and I deleted all files in the src
folder. Than I created index.js
and HelloWorld.jsx
files in the src
folder. Then I write these codes in these files. And I got empty page.
But I want to write Hello Mark
in the page. Why does it code give me an empty page?
index.js
file:
import React,{ Component } from 'react';
import HelloWorld from './HelloWorld';
class index extends Component {
render() {
return (
<div className="index">
<HelloWorld name="Mark" />
</div>
);
}
}
export default index;
HelloWorld.jsx
file:
import React,{ Component } from 'react';
const HelloWorld = (props) => (
<div>
<h2>Hello <em>{props.name}</em></h2>
</div>
);
export default HelloWorld;
Okay, so a few things:
First of all, change the name of your root component from index
to Index
. React components should start with a capital letter.
Then, you have to use ReactDOM.render()
at the root level. This is what actually initiates the rendering and reconciliation process of all subcomponents.
import React,{ Component } from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './HelloWorld';
class Index extends Component {
render() {
return (
<div className="index">
<HelloWorld name="Mark" />
</div>
);
}
}
ReactDOM.render(<Index />, document.getElementById("app"));
Note that you also need an index.html
file with a div
in the body with an id
attribute that matches the selector above (in this example "app
").