Register to get access to free programming courses with interactive exercises

Components JS: React

Here we'll be looking at an example in the lesson:

The central concept in React is the component.

Moreover, it's the only entity it contains. All other functionality works around components.

In the example above, we created a component that adds <div>Hello!</div> to the page DOM.

It is what the resulting HTML looks like:

<div id="react-root">
  <div>Hello!</div>
</div>

Imports

CodePen imports React automatically (you must specify it in the libraries you plug in), but you can't skip imports in your code:

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

Observing the code and imports, you can see that you need two libraries to work with React: React itself and ReactDOM. The reason for the two dependencies is quite simple. We do not direct link to the DOM and do not use it in the browser. It is why we put DOM-specific rendering in a separate package called ReactDOM.

Component

export default class Hello extends React.Component {
  render() {
    return <div>Hello</div>;
  }
}

A few obvious points

  1. A React component is a class that inherits from the React.Component class (as you'll see later, this isn't the only way to create a component)
  2. The render function returns something the browser will render. A class component without a render function cannot exist. It is its interface

We set the export default class for a reason. In JS, it's standard to create one class per file.

Unlike regular classes, React components have a JSX extension. It means that the component defined above must be in a file Hello.jsx.

The class is still named, although this isn't necessary in the case of default export. You can genuinely leave it unnamed. However, this can cause issues when using the React Dev Tools extension.

It happens because the tool will display unnamed components as <ReactComponent>, making it challenging to determine what React has rendered.

Therefore, it's best practice to give names to your components to make them easily identifiable in the extension.

A few less obvious points

The most striking thing happens in this line:

return <div>Hello</div>;

Common sense dictates that such notation is syntactically impossible in JavaScript, and that's not wrong.

Here you see the code is JSX. It is an extension of the JavaScript language added to the code via Babel. As you continue working with the React framework, you'll appreciate the benefits of using JSX.

The main thing to remember is that any React component eventually returns a piece of the DOM (actually a virtual DOM). By the way, div is also a React component, only built-in.

It's easy to distinguish between built-in components and self-written ones:

  • Built-in components always start with a small letter
  • Self-written components start with a capital letter

It's a good practice to give the .jsx extension to all files containing JSX, regardless of whether a component is created in that file.

Mount

const root = ReactDOM.createRoot(document.getElementById('react-root'));
root.render(<Hello />);

A created component (component class) by itself does nothing. To enjoy the result of its work, you need to do something called mounting. It's telling React where to put it in the DOM.

This task requires a DOM node. Any node within the body may be suitable. Usually, if you don't have a SPA, React is used in widgets plugged into the page in different places. There can be several widgets on one page at once. For example, on Hexlet, all the front-end elements are just widgets. An application container is created based on the node with a string:

const root = ReactDOM.createRoot(document.getElementById('react-root'));

Next, we mount the component in the container:

root.render(<Hello />);

We pass the component as a parameter in JSX syntax.

JSX

JSX is an XML-like markup extension for JavaScript designed specifically for React tasks. React comes out of the box with components that completely replicate HTML. For the most part, the syntax and structure of JSX and HTML are the same, but there are some differences:

  1. Since its syntax is similar to XML, single tags in JSX must be closed: <hr />
  2. Instead of the class attribute in JSX, we use the property name in the DOM: className

There are other differences, which we'll look at in future lessons. Most of these differences make working with the DOM inside React easier and more convenient.

Just as in HTML, you can build compositions out of components, like this one:

const vdom = (
  <div className="card">
    <div className="card-body">
      <h4 className="card-title">Card title</h4>
      <p className="card-text">my text</p>
      <a href="#" className="btn btn-primary">
        Go somewhere
      </a>
    </div>
  </div>
);

And this is all valid JS code with the JSX extension plugged in.

The fact that every React component returns a piece of the DOM is a consequence of its fundamental idea and architecture. We will discuss this idea in more detail in a future lesson, and you'll most surely get the hang of it. But why do we need to introduce JSX?

We should notice that JSX is an extension of the language, meaning it's code, not html. Since JSX translates into code, you can write that code right away. Right? True, but not quite:

React.createElement(
  "div",
  { className: "card" },
  React.createElement(
    "div",
    { className: "card-body" },
    React.createElement(
      "h4",
      { className: "card-title" },
      "Card title"
    ),
    React.createElement(
      "p",
      { className: "card-text" },
      "my text"
    ),
    React.createElement(
      "a",
      { href: "#", className: "btn btn-primary" },
      "Go somewhere"
    )
  )
);

The example code above is just what the render component functions would look like on React. However, this example is very trivial and contains no logic. If you had conditional constructs, this code would exceed all reasonable limits on the complexity of analysis. Assembling tree structures in code is a ruthless task. Now it should be a little clearer why JSX is needed, and that JSX is not a layout (as some people think).

One last thing. Since any JSX ends up being transformed into React.createElement calls, you need to check that React is imported: import React from 'react'.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.