Your very first React app
This section describes the main constituents of a React application
A minimal example, dissected
The snippet below shows a sampleindex.js
file, illustrating a minimal example of a complete React application.
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div>
<h1> Hello world! </h1>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Let's dissect it!
Part 1: Imports
import React from "react";
import ReactDOM from "react-dom";
Allright, the first import statement is needed to access all the React-specific syntaxes in the namespace of this file. An example of this JSX; when we import the react
-package, the JSX-syntax is understood.
Next, we need to import ReactDOM
, in order to render our JSX as a part of the React virtual DOM.
Part 2: React Component Declaration (official docs)
function App() {
return (
<div>
<h1>
Hello world!
</h1>
</div>
);
}
So, we need to create a React Component! This is actually nothing worse than creating a good ol' JavaScript function. The two main differences, however, is:
1. We uppercase the function name, indicating that we have a React Component
2. We need to return either one JSX-element (as here), or null
. Returning null
is the same as telling React to render nothing from this component.
Remember for later that each React Component should live in a separate file. This makes it reusable and nice!
Part 3: Render it! (official docs)
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In order to render our nifty JSX, we need to tell React what to render. The render
function from ReactDOM
takes two arguments; the root-element of your App and what HTML-element to append it to. We have both 💥
Assignment: Playtime!
The first assignment is to play around with the code we just dissected:
The first assignment is to get acquainted with the code at https://codesandbox.io/s/wq3j418p9w, and edit the code to see what happens!
Notice that we have a index.html
file under the /public
folder. This file contains the div
with the id
"root", which we rendered our React application inside index.js
.
Last updated