Register to get access to free programming courses with interactive exercises

Components JS: React

Take a look at the example we'll be looking at in the lesson.

The central concept in React is the component. Moreover, it's the only entity it contains. All other functionality is built around components.

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

This 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';

From 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. The React library itself is not directly linked to the DOM and isn't just used in the browser. This is why DOM-specific rendering is put in a separate package called ReactDOM.

Component

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

A few basic 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 (discussed later) that will be rendered in the browser. A class component without a render function cannot exist, it's its interface.

Export default class is set for a reason. In JS, it's standard to create one class per file. Unlike regular classes, React components have a JSX extension, which means that the component defined above must be in a file named Hello.jsx.

Note: the class is still named, although this isn't necessary in the case of default export. You can genuinely leave it unnamed, but then it'll be difficult to tell through the React Dev Tools extension what React drew, because any unnamed component will show up as <ReactComponent>. So make it a rule to always give your components a name.

A few less basic points

The most striking thing happens in this line:

return <div>Hello</div>;

Common sense dictates that such notation is syntactically impossible in JS. And that's not wrong. What you see is called JSX and it's an extension to the language (added with Babel). A pretty basic solution for a framework, isn't it? As you go on, you'll find that it's not such a bad idea.

The main thing to remember now 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 very easy to distinguish between built-in components and self-written ones. Embedded components always starts with a small letter, and those that are not part of React should start with a capital letter.

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

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. Basically, it's telling React where to put it in the DOM.

This task requires a real DOM node. Any node within bodymay be suitable. Typically, if you don't have an SPA, React is used in the form of widgets plugged into the page in different places. There can be several widgets on one page at once. For example, on Hexlet, all the frontend 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, the component is mounted in the container:

root.render(<Hello />);

A component is passed 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 a set of components that completely replicate HTML. For the most part, the syntax and structure of JSX and HTML are the same, but there are some important differences:

  1. Since this is a similar syntax to XML, single tags in JSX must be closed: <hr />.
  2. Instead of the class attribute in JSX, the property name in the DOM is used: 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. This idea will be discussed 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?

You have to understand that JSX is an extension of the language, which means that it's code, not html. And 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. Unfortunately, or fortunately, assembling tree structures in code (and the DOM is a tree) is a very hard and 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 transpiled into React.createElement calls, you need to make sure that React is imported: import React from 'react'.


Hexlet Experts

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

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

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.