Code

React for Beginners: What is this JavaScript library and how to use it

React for Beginners: What is this JavaScript library and how to use it

Placement course: "Web Developer"

Learn More

There are many React.js tutorials online with titles that imply simplicity, but most are difficult to understand. For someone without basic JavaScript knowledge, such materials can only confuse and cause a feeling of uncertainty. We decided to present information about React.js as clearly as possible, explaining what this tool is and what problems it solves. In addition, we will show how to use React.js to create a small online game, which will allow you to master the basics of this popular library.

You will learn how to effectively use SEO to improve the visibility of your content in search engines. We will discuss key aspects such as optimizing titles, creating unique meta descriptions, and using keywords. We will also consider the importance of internal and external linking structure, as well as content quality and its relevance to user queries. Understanding these principles will help you improve your website's ranking and attract more target audience.

  • What is React.js
  • What are components and states
  • Why do you need React.js
  • What are its analogues
  • Where to download it and how to start using it
  • How to write and set up a simple project in React.js

What is React.js

React.js is a JavaScript library developed by Facebook, designed for building user interfaces. It simplifies the development of the front-end of websites and applications, providing interactivity and convenience for users. React.js allows developers to effectively manage the state of components and create dynamic interfaces, which makes it a popular tool in web development.

The main feature of React.js is the use of components and state management. Components are the building blocks of interfaces, allowing developers to create reusable and easily scalable elements. State management provides the ability to track and modify data, making applications more interactive and responsive. Effective use of components and state in React.js ensures high performance and simplifies the development process.

A component is a fragment of code that is responsible for the visual design of a single element of a website or application. These components can be nested, allowing for the creation of more complex and multi-level structures. Using components helps simplify development, improve code readability, and increase reusability.

An element's state includes complete information about its characteristics, including visual aspects. For example, the state of a thermometer might be represented by properties such as the current temperature (current_temperature) and minimum and maximum temperatures (min and max). These parameters allow us to accurately describe and visualize the thermometer's functionality, providing users with the necessary information about its operation.

What are components and states: translating into understandable language

While this may seem abstract and complex at first glance, in practice everything is much simpler. Let's consider the example of Mark Zuckerberg: this is his project, and he is responsible for its development and functioning.

The screenshot shows three main components: a post in the Facebook feed, a block with brief information, and a block with photos. Each of these components includes smaller elements. For example, a post contains text, an image, the author's avatar, their name, the number of likes, comments, and other informational elements. The photo block contains individual images, while the summary block contains the essence of the content presented.

Screenshot: Skillbox Media

Each component in React.js has its own state. For example, a summary block displays differently on mobile and desktop versions. The like button's number of likes and color change depending on whether a like has been given. A post can display its full text or have it truncated, which also depends on its content. The post's content is an important state. The flexibility and power of React.js allows developers to create components once and then pass them different states, simplifying the development process and improving the user experience.

Explore how the avatar size changes depending on the state.

Screenshot: Skillbox Media
  • Large - in the header of the personal page.
  • Standard - in the top menu and posts in the feed.
  • Very tiny - in the line "you have so many subscribers."

Currently, three avatar states have been developed, but this is far from the limit. The appearance of the avatar varies depending on the platform: mobile and desktop versions, as well as applications for Android and iOS, have their own characteristics. It is important to note that the avatar is usually a nested component within larger React.js elements, such as posts, headers, sidebars, and menus. This makes it an important interface element that requires a careful approach to design and functionality to ensure an optimal user experience.

React.js provides tools for managing application state, but medium and large projects most often use Redux, a third-party state manager. Redux provides more convenient state management and scales better, making it the preferred choice for complex applications. Using Redux allows you to effectively organize your application architecture, simplifies debugging and testing, and promotes more predictable application behavior.

Why Use React.js When You Have HTML, JavaScript, and CSS?

React.js is a powerful tool for conveniently representing JavaScript and HTML code, allowing you to create repeatable and visual interfaces. The core element of React are components, which are developed using JSX, a special syntax that combines JavaScript and HTML. JSX simplifies the creation of user interfaces, making the code more readable and understandable. This JSX code example demonstrates how easy it is to integrate logic and markup, ensuring high performance and ease of development.

JSX code is clear, and although it resembles HTML, it is not actually HTML. This may seem unusual, but it is actually just JSX syntax, designed to simplify working with components in React. JSX allows developers to create interfaces by combining JavaScript and markup, simplifying the development process and improving code readability.

The browser does not require knowledge of JSX, as code written in React.js is transpiled into JavaScript, which is supported by all modern browsers. To achieve this, React.js applications are processed using Babel, a transpiler tool that converts various formats, such as JSX, into standard JavaScript. This allows developers to use the convenient JSX syntax while maintaining browser compatibility and ensuring correct application execution.

JSX is an extension of JavaScript syntax that allows you to write elements in a format similar to HTML. It is used in the React library for creating user interfaces. JSX simplifies the structure of components, making the code more readable and easier to understand. The main idea of ​​JSX is to combine JavaScript logic and markup in a single file, which contributes to faster development and improved application performance.

When using JSX, it is important to remember about the correct spelling of elements. All tags must be closed, and attributes are written in camelCase. For example, instead of the standard HTML attribute «class», JSX uses «className». This avoids conflicts with JavaScript reserved words. JSX also supports JavaScript expressions within curly braces, allowing you to dynamically modify the contents of components.

JSX makes React development more intuitive and efficient. It allows developers to quickly create and modify interfaces, significantly speeding up the development process. Using JSX, you can easily integrate logic and visual representation, improving user interaction with the application.

At first glance, the mechanics may seem strange. It's similar to Dostoevsky creating his own language, writing his works in it, and then translating them into Russian and publishing. However, this analogy would only be appropriate if Dostoevsky's books were translated automatically, and the writing process in the new language were significantly accelerated.

React.js has three key advantages. First, its high performance is ensured by a virtual DOM, which minimizes the number of operations with the real DOM, significantly speeding up interface updates. Secondly, React.js offers a component-based approach to development, which promotes code reuse and simplifies application state management. Thirdly, an active community and a rich ecosystem of libraries and tools make React.js a popular choice among developers, making it easy to find solutions to various problems and get help. These advantages make React.js an excellent choice for building modern web applications.

  • JSX is much easier to read and understand than JavaScript, which means that developers spend much less time on maintaining and debugging code (which means salaries and the speed of new releases).
  • It conveniently implements a system of components—repetitive pieces of code that are used in different conditions and circumstances and change depending on the context.
  • Each component depends only on its own state—which means it is much easier to debug errors in the code if something does not work or does not work as expected. This means that errors become obvious: a component that works correctly on its own will always work correctly—unless you pass it some incorrect state.

React.js significantly saves development time, improves code readability and structure, and enables the reuse of large components. This leads to a significant reduction in the costs of developing, maintaining, updating, and debugging applications, and also increases their speed. Mastering React.js is easy if you have basic skills in JavaScript and HTML—learning the basics usually takes only a few days. However, it is worth noting that React.js is most effective for projects with a large number of dynamic pages. Using it to create simple business card websites is impractical.

React.js Competitors

React.js has its competitors, among which the most popular libraries are Vue.js and Angular. Each of these technologies is designed for building user interfaces and has its own advantages and disadvantages. Currently, employers prefer knowledge of React.js: according to data from March 2023, this requirement was found 3,300 times on hh.ru, while Vue.js was mentioned 1,782 times, and Angular was mentioned 1,282 times. This demonstrates the high demand for developers proficient in React.js, making it an essential skill for web development professionals.

According to Stack Overflow research, React.js ranked second among the most popular web frameworks in 2022, behind only Node.js. This framework overtook the outdated jQuery library, which, despite negative developer sentiment, remains actively used. jQuery was previously the foundation of many websites and applications, and rewriting their code is not always practical. The Express framework for Node.js ranked fourth in the ranking. Meanwhile, competitors React.js, Angular, and Vue.js ranked fifth and sixth, respectively. This data highlights the growing popularity of React.js and its importance in modern web development.

Screenshot: Stack Overflow

There is also React Native, developed by Facebook, which should not be confused with React.js. At some point, Facebook realized that React.js was being used to build not only web applications but also apps for various operating systems. However, these apps were often slow. To improve performance, Facebook developed a native version of the library, enabling the creation of efficient cross-platform apps using JavaScript. React Native allows developers to write code once and run it on iOS and Android, significantly simplifying the process of developing and maintaining mobile apps. React Native's syntax is based on JSX, but it is transformed into a language that is understandable and familiar to operating systems such as Windows, macOS, and Android. This allows for the creation of native apps that utilize the standard capabilities and protocols of each platform, rather than relying on a browser. Additionally, React Native supports integration with other programming languages, such as Java, Swift, and Objective-C, expanding development options and simplifying the process of creating cross-platform applications.

Where to download React.js and how to get started

There are two ways to access React.js. The first method involves downloading the library via a CDN, which allows you to quickly start developing without installing additional tools. The second method involves installing React.js using package managers such as npm or yarn, which provides a more flexible and manageable development process. Using these methods allows developers to easily integrate React.js into their projects and use it to create dynamic user interfaces.

This is the most convenient way to work with HTML and JavaScript. You can experiment with libraries in online sandboxes such as CodePen and CodeSandBox. You can also download an HTML template from GitHub. Afterwards, you can use Babel to compile your code online, eliminating the need to install additional applications. This approach allows you to quickly test and implement changes, significantly simplifying the development process.

Installing and setting up a full-fledged React.js development environment requires a significant investment of time and is recommended for more advanced users.

Before installing and configuring the server, you must install Node.js. This runtime environment allows you to run JavaScript code as a server-side application. Installing Node.js is the first step to developing server-side JavaScript applications.

To get started, download the create-react-app package using npm. This will allow you to quickly set up a new React-based application, providing a standard project structure and pre-installed dependencies. Make sure you have Node.js and npm installed for this to work.

Once the module installation is complete, create a template application using the following command:

If all operations are successful, Node.js will print "Happy hacking!" at the end of the message.

Run the application to perform the necessary tasks and improve your workflow. Make sure all system requirements are met to ensure stable operation. After running the application, you will be able to access its functionality and optimize the execution of tasks. If any issues arise, check the settings and update the application to the latest version for maximum performance.

We used the cd command to move to the project directory, and used the start command to start the local development server at http://localhost:3000/. After this, the expected content should be displayed in the browser. Make sure all elements load correctly and you see the desired interface of your application.

Image: Skillbox Media

Development and configuration of a simple React Applications

We'll create a web version of the classic tic-tac-toe game using React.js. All code, except for styles, will be located in the App.js file in the src directory. This game will be simple and interactive, making it an ideal project for learning the basics of React.

We'll import the React module, along with the necessary webhooks from it, and the ReactDOM library, which will provide rendering of components in the application. This is the first step in creating an interactive user interface using React.

In the App component, we'll implement the game logic. You can delete the existing code, as we won't need it for further development.

Using the useState hook, we'll create functionality that returns an array of squares. This array will store the state of the playing field's cells. This way, we can manage the state of each square, which will allow us to efficiently update the interface and track changes in the game.

At the start of the game, the squares array will be initialized with nine empty elements. The setSquares function will change the state of this array as needed.

Let's create an additional hook for managing the player queue in the game, which will determine whose turn it is: player X or player O. This hook will allow us to efficiently track which player makes a decision next, which will improve the gameplay and make it more organized. Proper implementation of this hook will ensure stability and predictability during the game, which will positively impact the user experience.

By default, the game state is set to true, which means that players using crosses go first. The setXIsNext function is responsible for switching the turn order between players.

At each turn of the game, it is important to check whether a winner has been determined. To do this, we'll create a calculateWinner function, which will analyze the current situation on the playing field and determine whether a player has achieved the winning conditions. This function will test all possible combinations to determine the winner, which is key in developing game logic. Proper implementation of the calculateWinner function will ensure accurate determination of the winner and improve gameplay.

The calculateWinner function accepts an array with the current values ​​of the game board squares. The function contains a lines array containing all possible winning combinations. The function analyzes these combinations, substituting indices from the input array. If all three values ​​in one of the combinations match, the function returns the winner (X or 0). If there is no winner, the function returns null.

The winner variable contains a value that determines the winner.

To streamline player interaction with the game interface, it is necessary to use the handleClick function. This function will be triggered when a click on the game board occurs. When it is called, a copy of the squares array is created, and a check is made to see if the current player can move to the selected square. If a move is possible, the function modifies the squares array and the player's state, ensuring alternating moves. This will create an interactive and user-friendly gaming experience where every player can actively participate in the game, and the interface will be responsive and intuitive.

The renderSquare function is responsible for creating the game board cells, which are regular HTML buttons. It takes the square number as a parameter and returns a button that can be clicked to make a move. This implementation allows for interactive interaction with the game board, allowing the user to actively participate in the game.

The program should display the game status on the game board. If a winner has been determined, the status will indicate this using the phrase "Winner: X" or "Winner: 0". If there is no winner, the status will indicate whose turn it is next and will look like "Next player: X" or "Next player: 0".

In this section, we will create the JSX elements that the App function will return. These elements will be directly displayed on the page and form the user interface of the application. Proper structure of JSX elements will ensure correct content display and improve user experience.

First, the game status is displayed, after which each cell of the playing field is created using the renderSquare function. This process provides visualization of gameplay and allows players to easily navigate the current state of the game.

To ensure that the game interface has an attractive appearance and that cells do not go beyond the boundaries of their rows when interacting, it is necessary to properly configure the page styles. In the styles.css file, save the following code:

To include the file, use the import directive. This allows you to integrate the contents of one file into another, providing a more organized structure of your code. Make sure that the path to the file is specified correctly to avoid loading errors. This practice helps simplify the management of styles and scripts, improving the performance and readability of your project.

Add the flex class to each div element with the className=board-row attribute. This will improve the display and structure of your content, providing flexible arrangement of elements within rows. Optimization using flexbox will help achieve better visual perception and responsiveness on different devices.

Keep in mind that in JavaScript, the word class is reserved for other functions. Therefore, the className property is used to specify the class name of an element. This is an important point for developers, as the correct use of className allows you to effectively manage the styles and behavior of elements on a web page.

The project code is the structured foundation on which the functionality of a web application is built. It includes HTML, CSS, and JavaScript, ensuring interaction between the user and the server. It is important that the code is organized and easy to read, which facilitates its further development and support.

The HTML code structure includes semantic tags, which improves page indexing by search engines. CSS is responsible for the visual design, allowing you to create a responsive design that will display correctly on different devices. JavaScript adds interactivity, allowing users to interact with page elements.

Every element of the code should be optimized to improve page load speed and user experience. Using comments and logically organized code blocks will make it more understandable for both developers and search engines.

The project code should be thoroughly tested on various browsers and devices to ensure its stable operation and compliance with modern web development standards. Optimizing images, minifying files, and proper caching will help achieve high performance and SEO.

Ultimately, well-written and optimized project code is the key to a successful web application capable of attracting and retaining users.

A game in a browser window should have an intuitive interface and high-quality graphics. It is important that the controls are convenient and responsive, which will provide a comfortable gaming experience for users. It is also necessary to optimize the game for various devices so that it displays correctly on both desktop computers and mobile devices. A convenient layout of game elements and clear navigation will help players quickly get the hang of the game. Additionally, it's worth paying attention to the game's loading speed, as this directly impacts the user experience. Visual effects, animation, and sound should also create atmosphere and hold players' attention.

Image: Skillbox Media