React apps are actually made out of components
What's a Component?
Components are reusable chunks of code that's responsible for one job. That job is often to render HTML.
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponentClass extends React.Component {
render() {
return <h1>Hello world</h1>;
}
};
ReactDOM.render(
<MyComponentClass />,
document.getElementById('app')
);
Let's unpack this code, line by line:
import React from 'react';
This line of code creates a new variable, React
and its value is an important JavaScript object. The object is the React library.
import ReactDOM from 'react-dom';
Line two is similar from line one, but we're importing the React library that interact with the DOM.
class MyComponentClass extends React.Component {}
Every component must come from a component class. To make a _component class, _you use a base class from the React library: React.Component
.
React.Component
is a JavaScript class. To create your own component class, you must subclass React.Component
. You do this with the syntax: class x extends React.Component {}
.
(More on classes and subclasses: 1, 2, 3, 4.)
As an aside, component class names are always written in UpperCamelCase.
render() {
return <h1>Hello world</h1>;
}
The render method has to be included within the component class instructions. The render method must contain a return
statement, usually a JSX expression.
ReactDOM.render(
<MyComponentClass />,
document.getElementById('app')
);
To call our MyComponentClass
, we have to pass it to ReactDOM.render()
. ReactDOM.render()
will tell MyComponentClass
to call its render method, which will return
the JSX element <h1>Hello world</h1>
. ReactDOM.render()
will take that resulting JSX element, and add it to the virtual DOM. This will make "Hello world" appear on the screen.