Ātrs ceļvedis, kas palīdzēs saprast un izveidot ReactJS lietotnes

Šis ziņojums ir sadalīts 2 daļās

  1. Pirmajā daļā ir parādīts, kā izveidot vienkāršu lietotni React, izmantojot CLI 'create-reaģēt-app', un paskaidrota projekta struktūra.
  2. Otrajā daļā izskaidrots esošais kods, kuru esmu ievietojis vietnē Github. Šis kods parāda komponentu izmantošanu, saziņu starp komponentiem, HTTP zvanu veikšanu un React Bootstrap (sāknēšanas siksna, kas ir rakstīta React).

1. daļa

Instalējiet NodeJS, ja tas vēl nav pieejams

NodeJS ir nepieciešams, jo Reactage nepieciešamās bibliotēkas tiek lejupielādētas, izmantojot mezglu pakotņu pārvaldnieku (npm). Lai instalētu NodeJS, skatiet vietni //nodejs.org/en/.

Instalējiet create-reaģēt-app mezglu pakotni

mezgls create-reaģēt-app palīdz iestatīt React projektu. Instalējiet create-reaģēt-app mezglu pakotni visā pasaulē, izmantojot šo komandu.

npm install -g create-react-app

Izveidojiet projektu

Projektu var izveidot, izmantojot izveidot-reaģēt-lietotni. Lai izveidotu projektu, izmantojiet šo komandu.

npx create-react-app first-react-app

first-react-app ir lietojumprogrammas nosaukums. Iepriekš minētā komanda izveido mapi ar nosaukumu first-react-app, kas ir projekta mape. Lai pārbaudītu, vai viss ir iestatīts pareizi, dodieties uz projekta mapi un palaidiet lietojumprogrammu, izmantojot šādu komandu.

cd first-react-app npm start

Dodieties uz savu pārlūkprogrammu un dodieties uz šādu vietrādi URL : 3000

Jums vajadzētu redzēt, ka jūsu lietojumprogramma darbojas. Lietojumprogramma jūsu pārlūkprogrammā izskatīsies šādi:

Paskaidrota pamata mapju struktūra

Veidojot projektu, jūs pamanījāt, ka tas izveidoja virkni failu. Šeit es uzskaitīšu dažus svarīgus failus un mapes, kas jums būtu jāzina.

  1. package.json: Šajā failā ir nepieciešamo mezglu atkarību saraksts.
  2. public / index.html: Kad programma tiek palaista, tā ir pirmā ielādētā lapa. Šis būs vienīgais HTML fails visā lietojumprogrammā, jo React parasti tiek rakstīts, izmantojot JSX, kuru es aplūkošu vēlāk. Arī šim failam ir koda rindiņa. Šī līnija ir ļoti nozīmīgs, jo visi pieteikumu sastāvdaļas ir Loades d i nLai šo div.
  3. src / index.js : Šis ir Javascript fails, kas atbilst index.html. Šim failam ir šāda koda rindiņa, kas ir ļoti nozīmīga. ReactDOM.render (, document.getElementById ('root'));
  4. Iepriekš minētā koda rindiņa norāda, ka App Component (drīzumā tas aptvers App Component) ir jāielādē html elementā ar id root . Tas ir nekas cits kā indekss index.html esošais div elements .
  5. src / index.css : CSS fails, kas atbilst index.js.
  6. src / App.js : Šis ir App Component fails . Lietotnes komponents ir galvenā React sastāvdaļa, kas darbojas kā konteiners visiem pārējiem komponentiem.
  7. src / App.css : Šis ir CSS fails, kas atbilst App Component
  8. būvēt: Šī ir mape, kurā tiek saglabāti uzbūvētie faili. React Apps var izstrādāt, izmantojot vai nu JSX, vai arī pašu parasto JavaScript, taču JSX izmantošana noteikti atvieglo izstrādātāja kodēšanu :). Bet pārlūkprogrammas nesaprot JSX. Tātad pirms izvietošanas JSX ir jāpārvērš javascript. Šie pārveidotie faili pēc apvienošanas un sasmalcināšanas tiek saglabāti būvniecības mapē. Lai redzētu būvēšanas mapi, izpildiet šo komandu
npm run build 

Komponentu veidošana

React komponents veic noteiktu funkcionalitāti. Lietojumprogramma ir nekas cits kā komponentu kolekcija. Katram komponentam var būt vairāki pakārtoti komponenti, un komponenti var savstarpēji sazināties.

Tagad izveidosim React Component.

Iekš src izveidojiet failu ar nosaukumu FirstComponent.js un nokopējiet šādu kodu mapē FirstComponent.js.

import React, {Component} from 'react'; export default class FirstComponent extends Component { constructor(props) { super(props) } render() { const element = ( Text from Element ) return ( 

First Component

{this.props.displaytext} {element} ) } }
  1. Komponenta nosaukums ir FirstComponent, ko apzīmē ar faila nosaukumu, kā arī paziņojumāexport default class FirstComponent extends Component
  2. Aksesuārus atribūts konstruktors ietvers visus parametrus, kas nodoti par ieguldījumu šo komponentu.
  3. render (): ekrānā tiek atveidota (parādīta) šīs funkcijas atgriešanās vērtība. Ikreiz, kad renderēšanas () funkciju sauc, ekrāns tiek atkārtoti parādīts. Lietojumprogramma to parasti veic automātiski. Kods, kas šajā funkcijā izskatās ļoti līdzīgs html, nav nekas cits kā JSX.

JSX

JSX izskatās ļoti līdzīgs HTML, bet tam ir pilna Java spēka spēja. Šeit es izskaidrošu JSX kodu un to, ko tas mēģina darīt.

render() { const element = ( Text from Element ) return ( 

First Component

{this.props.displaytext} {element} ) }

Pirmā rinda const element = ( Text from Element )Izveido div elementu un piešķir to konstantei, ko sauc par elementu. Šī savdabīgā sintakse, kuru jūs redzat, nav nekas cits kā JSX.

Izraksta Return iekšpusē redzat šādu koda sintaksi.

First Component

{this.props.displaytext} {element}

Šeit className tiek izmantots, lai norādītu uz CSS klasi.

First Component

ir tikai parasta HTML sintakse. {this.props.displaytext}tiek izmantots, lai piekļūtu atribūtam, ko no rekvizītiem sauc par displaytext (tātad displaytext tiek nodots kā ievade ikreiz, kad tiek izsaukts šis komponents). Šeit displeja teksts ir tikai pielāgots nosaukums, kuru esmu devis . {element}ir izveidotā konstante, kas savukārt satur div elementu.

Using the Component

FirstComponent has been created but is not being used anywhere yet. Let's add FirstComponent to App Component. Here is the modified code for App.js

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import FirstComponent from './FirstComponent' class App extends Component { render() { return ( 

Welcome to React

To get started, edit src/App.js and save to reload.

); } } export default App;

FirstComponent needs to be imported into App Component First which is done in the line import FirstComponent from ‘./FirstComponent’

Then FirstComponent is added to App Component using the line

Here displaytext is passed as an attribute to the FirstComponent.

Now you can run the Application using the command npm start

You should see the following result in the browser.

Congrats?

Now you know how to create a React Application and how to create and use React Components. You also know a bit about JSX :)

The next part will explain an existing React Code from Github. Part 2 code is different from the code that we wrote in Part 1.

Part 2

Code

The Following Code is being explained here so clone the repo into your computer. The Repo has instructions on how to clone and set up the code in your computer.

//github.com/aditya-sridhar/simple-reactjs-app

Application URL

To see how the final Application looks like you can click on the following URL. This will give a good idea as to what the Application is trying to do

//aditya-sridhar.github.io/simple-reactjs-app

The Application would look like this in a mobile screen

What does this Application do

This application displays a list of customers. When a customer is selected, it displays the details of the selected customer. This is a Single Page Application (SPA). React is best suited for Single Page Applications. Single Page Applications display everything within a single page.

Application Structure Explained

Customers Component

This Component displays the list of Customers. This corresponds to the file src/Customers.js . This component has the following constructor.

constructor(props) { super(props) this.state = { selectedCustomer: 1 } }

props were already explained. But here you also see this.state. Whenever state changes, the component is rerendered. Here state has one parameter called selectedCustomer which is to keep track of which customer is selected. If selectedCustomer changes then the component and its child components are rerendered. The Constructor is used only to set props and state. Also, props should never be edited inside a component.

The next thing you notice is the following code.

componentDidMount() { this.getCustomerData(); }

componentDidMount() is a function which is called as soon the component is rendered. So this can be used to set some initial values as well as load data. Here it is calling a function called as getCustomerData()

The next piece of code that you see is

getCustomerData() { axios.get('assets/samplejson/customerlist.json').then(response => { this.setState({customerList: response}) }) };

This function getCustomerData() makes an HTTP call to read the sample json containing the list of customers from assets/samplejson/customerlist.json. On successfully getting a response, the state of the system is changed, by assigning the response to customerList. You may wonder why we never added customerList in the constructor. The reason is you can add parameters dynamically into State at any point in the code. The only requirement is that in the constructor at least an empty state has to be defined.

Here axios library is used to make the HTTP call. I have provided the Documentation for axios in the References section.

The next function is the render() function which returns what elements have to be rendered on screen. The main points of focus in the render function are

 this.setState({selectedCustomer: customer.id})}> Click to View Details 

Every customer in the list has a button called as Click to View Details. The above code snippet tells that whenever the button is clicked, then change the state of selectedCustomer to the selected customers' id. Since the state changes here, the component and its child component will be rerendered.

The other code snippet which is important is

This snippet tells that CustomerDetails is a child component of Customers component and also passes the selectedCustomer id as an input to CustomerDetails component

CustomerDetails Component

This component displays the details of the selected Customer. Some important code snippets from this component will be explained here:

componentDidUpdate(prevProps) { //get Customer Details only if props has changed //(props is the input) if (this.props.val !== prevProps.val) { this.getCustomerDetails(this.props.val) } }

componentDidUpdate() function is called whenever the component is rerendered. Here we are calling getCustomerDetails() Function if the input to this component has changed when the component rerendered. The input passed to getCustomerDetails() function is this.props.val. this.props.val in turn, gets its value from Customers Component( selectedCustomer was passed as an input to this ). To know if the input has changed, the code snippet used is this.props.val !== prevProps.val

getCustomerDetails(id) { axios.get('assets/samplejson/customer' + id + '.json').then(response => { this.setState({customerDetails: response}) }) };

getCustomerDetails() function makes an HTTP call to get the sample json which contains the customer details. The id parameter is used to know which customers details are required. id is nothing but this.props.val. When the response is successfully received the state of this component is changed by assigning response to customerDetails.

The render() function for this component is pretty straightforward and simple so will not be covering that here

References

create-react-app: Refer to //github.com/facebook/create-react-app to learn what all can be done using create-react-app

ReactJS: Refer to //reactjs.org/ to understand the concepts of ReactJS. The documentation is very good.

React Bootstrap: Refer to //react-bootstrap.github.io/getting-started/introduction/ to understand how to use React Bootstrap

axios: Refer to //www.npmjs.com/package/axios to know more about how to use axios library to make HTTP requests

Congrats Again ?

Now you know how to use components, how to communicate from a parent to a child component and also a little about rendering

The basic concepts have been covered in this post and hope this is helpful

About the author

I love technology and follow the advancements in technology. I also like helping others with any knowledge I have in the technology space.

Feel free to connect with me on my LinkdIn account //www.linkedin.com/in/aditya1811/

Varat arī man sekot vietnē twitter //twitter.com/adityasridhar18

Mana vietne: //adityasridhar.com/

Citas manis saistītās ziņas

Īsa rokasgrāmata, kas palīdzēs izprast un izveidot Angular 6 lietotnes

Ātrs ievads vietnē Vue.js