The First Steps to Understanding React | DevsDay.ru

IT-блоги The First Steps to Understanding React

DZone Web Dev 16 января 2022 г. Enrique Molinari


In this post I will give you - what I think - are the most important concepts to start dominating React.

For years we have seen back-end programming languages evolve. Evolve to accommodate new features and tools towards making software maintainable. From syntactical constructions like classes and objects, to namespaces, packages and modules. With great tools like those that help you to manage dependencies (maven, gradle, composer, pip, gems, etc) and those to automate the testing. Aligned with these, the software development community writing books and articles about best practices, patterns, refactoring techniques plus different proposals about how to architect your application: layered, modular, hexagonal (clean), onion, modular monolith, SOA, event-driven, microservices, etc.

On the other hand, at the front-end, we did the best we could. With almost zero tools or bibliography related to helping us write maintainable software. Most of us had to deal with a server-side template engine (PHP, JSP, JSF, freemarker, etc), mixing HTML, CSS, and jquery. At some point, JavaScript was considered a serious language thanks primarily to GMail, which shows how powerful a (single-page) Web application can be.  With the community screaming for better tools, Node.js proposed server-side JavaScript, and a tool to manage dependencies was created (npm). In addition, the Javascript language, in the ES6 release, evolved with many new features, especially the addition of modules. 

Taking advantage of these improvements, React was released incorporating to the front-end the idea of building applications by assembling self-contained components.  Does it sound that nothing really new was added? You are correct, we have been reading for years about the “self-contained components” silver bullet in those old books about software engineering. However, I believe React developers have done a great job providing the tool to make this real. In React, you design applications by assembling components, which are built by using plain JavaScript functions

The people behind React’s design decisions have challenged very established patterns like MVC, where you have the display logic and the markup separated in different abstractions. In React you have the display logic (fetching data, event handling, etc) and the markup in the same abstraction: the component. And each component represents a fragment of the functionality of your View. This is what makes React so great and the reason I love it. 

Without the details (that you should learn if you want to start coding in React), by using some pseudo-React code, let me explain to you the idea of how to build an application by assembling components. 

Suppose we want for our application a pretty simple layout, with a menu header and a body that contains a list of tasks like shown on the figure below:

Task list sample application                                                        Figure 1: Task List Sample Application

With this in mind, we are going to craft two components: Menu and TaskList. The Menu component will be responsible for building the top header with the label “Task List”. And the TaskList component will have the responsibility of obtaining and displaying the task list.

In your Rect application entry point (usually the App.js component), you can write something like:

JSX
 
function App() {
 return (
  <div>
    <Menu />  
    <TaskList />
  </div>
 );
}

The function above represents the main component called App. What that function component returns is called JSX (JavaScript XML). A JavaScript extension was proposed by React to paint the UI. What we are doing with the App component above is to instantiate the Menu and TaskList component (to use a term known from OOP). In other words, we are asking React to render these components, in that order (first Menu, then TaskList) as children of a <div> element. The Menu component paints itself as a <header> element, see below:

JSX
 
function Menu() {
 let title = “Task List”;
 return (
   <header>
     <span>{title}</span>
   </header>
 );
}

Note from above, the variable title in curly braces in JSX. You can wrap any JavasScript expression between them.  Let’s continue reviewing how the TaskList component gets the task and displays them:

JSX
 
function TaskList() {	
  let tasks = initializeState([ ]);          

  function afterFirstRender() {
     fetch(“https://my.endpoint.com/tasks”)
       .then((response) => response.json())
       .then((json) => setState(json));
  }

  return (
   <section>
    <p>Tasks List</p>
    <table>
     <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Expiration Date</th>
     </tr>
     {tasks.map((aTask) => (
     <tr>
      <td>{aTask.id}</td> 			
      <td>{aTask.name}</td>
      <td>{aTask.expirationDate}</td> 
     </tr>		
    ))}
   </table>
  </section>
 );
}

Like objects in OOP, React components have a state and a set of functions associated with their lifecycle. For instance, in OOP, the constructor is called at creation. If you look at the TaskList component above, in the first line we are initializing its state,  with an empty array. We then define a function called afterFirstRender and then the return statement of the component’s function. The first thing React does is to render the component (by invoking the component’s function), which means, processing the JSX (transforming it into HTML) and inserting the transformation into the DOM. At that point, the tasks state variable is still an empty array.  If we pause the execution right now, we will notice by looking at the browser, that the component has been rendered. Looking like in the image below:

Empty Table task list

                                                                         Figure 2: Empty Table

After the rendering is finished, the afterFirstRender function is invoked by React (this is one of the lifecycle functions). This function, by using the JavaScript fetch function, obtains the tasks from an API, transforms them into JSON, and saves them into the tasks state variable, using the especial setState function. This special function, after assigning the value to the variable, triggers the re-render of the component, painting the cells of the <table> with the task data (since now the tasks state variable has been updated). And now, if we look at the browser we will see what is shown in figure 1. Please, note how nice this was. TaskList is really a self-contained component. It was able to get the data from an API and to paint itself into the DOM.  

These were what I consider the main concepts you should learn if you want to start coding in React: self-contained components, JSX, State, and lifecycle functions. There are many other and more examples you can find in the book Understanding React.

Источник: DZone Web Dev

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

javascript tutorial web dev coding reactjs coding basics