En hurtig guide til at hjælpe dig med at forstå og oprette ReactJS-apps

Dette indlæg er opdelt i 2 dele

  1. Første del demonstrerer, hvordan man opretter en simpel React-app ved hjælp af 'create-react-app' CLI og forklarer projektstrukturen.
  2. Anden del forklarer en eksisterende kode, som jeg har sendt i Github. Denne kode demonstrerer brugen af ​​komponenter, kommunikation mellem komponenter, foretage HTTP-opkald og React Bootstrap (bootstrap, der er skrevet til React).

Del 1

Installer NodeJS, hvis den ikke allerede er til stede

NodeJS er nødvendig, da biblioteker, der kræves for at reagere, downloades ved hjælp af node-pakkehåndtering (npm). Se //nodejs.org/en/ for at installere NodeJS.

Installer create-react-app Node-pakke

create-react-app node-pakke hjælper med at oprette et React-projekt. Installer node-pakke for create-react-app globalt ved hjælp af følgende kommando.

npm install -g create-react-app

Opret projektet

Projektet kan oprettes ved hjælp af create-react-app. Brug følgende kommando til at oprette projektet.

npx create-react-app first-react-app

første reaktion-app er navnet på applikationen. Ovenstående kommando opretter en mappe kaldet first-react-app, som er projektmappen. For at teste, om alt er konfigureret korrekt, skal du gå ind i projektmappen og starte applikationen ved hjælp af følgende kommando.

cd first-react-app npm start

Gå til din browser, og gå til følgende URL localhost: 3000

Du skal kunne se, at din applikation kører. Applikationen ser sådan ud i din browser:

Grundlæggende mappestruktur forklaret

Når du oprettede projektet, ville du have bemærket, at det oprettede en masse filer. Her viser jeg nogle af de vigtige filer og mapper, som du bør være opmærksom på.

  1. package.json: Denne fil har listen over nodeafhængigheder, der er nødvendige.
  2. public / index.html: Når applikationen starter, er dette den første side, der indlæses. Dette vil være den eneste html-fil i hele applikationen, da React generelt er skrevet ved hjælp af JSX, som jeg vil dække senere. Denne fil har også en linje med kode. Denne linje er meget vigtig, da alle applikationskomponenterne lægges i denne div.
  3. src / index.js : Dette er javascript-filen, der svarer til index.html. Denne fil har følgende kodelinje, som er meget vigtig. ReactDOM.render (, document.getElementById ('root'));
  4. Ovenstående kodelinje fortæller, at App Component (snart dækker App Component) skal indlæses i et html-element med id- rod . Dette er intet andet end div-elementet, der findes i index.html.
  5. src / index.css : CSS-filen, der svarer til index.js.
  6. src / App.js : Dette er filen til App Component. App- komponent er hovedkomponenten i React, der fungerer som en beholder til alle andre komponenter.
  7. src / App.css : Dette er CSS-filen, der svarer til App Component
  8. build: Dette er den mappe, hvor de indbyggede filer er gemt. React Apps kan udvikles ved hjælp af enten JSX eller selve JavaScript, men ved hjælp af JSX gør det bestemt nemmere at kode for udvikleren :). Men browsere forstår ikke JSX. Så JSX skal konverteres til javascript inden implementering. Disse konverterede filer gemmes i buildmappen efter bundling og minificering. For at se build-mappen Kør følgende kommando
npm run build 

Oprettelse af komponenter

En komponent i React udfører en bestemt funktionalitet. En applikation er kun en samling af komponenter. Hver komponent kan have flere underordnede komponenter, og komponenterne kan kommunikere med hinanden.

Lad os oprette en reaktionskomponent nu.

Inde i src- mappen skal du oprette en fil kaldet FirstComponent.js og kopiere følgende kode til 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. Komponentnavnet er FirstComponent, der betegnes med filnavnet såvel som i erklæringenexport default class FirstComponent extends Component
  2. Den rekvisitter attribut i konstruktøren vil indeholde alle de parametre, der overføres som input til denne komponent.
  3. render (): Returneringsværdien for denne funktion gengives (vises) på skærmen. Hver gang render () -funktionen kaldes, gengives skærmen. Dette gøres normalt automatisk af applikationen. Koden, der ligner meget html i denne funktion, er intet andet end JSX.

JSX

JSX ligner meget HTML, men har den fulde kraft af javascript. Her vil jeg forklare JSX-koden, og hvad den prøver at gøre.

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

First Component

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

Den første linje const element = ( Text from Element )Opretter et div-element og tildeler det til et konstant kaldet element. Denne ejendommelige Syntaks, at du ser, er noth ing men JSX.

Inde i Return-sætningen ser du følgende kodesyntaks.

First Component

{this.props.displaytext} {element}

Her bruges className til at pege på en CSS-klasse.

First Component

er bare normal html-syntaks. {this.props.displaytext}bruges til at få adgang til en attribut kaldet displaytekst fra rekvisitter (så displaytekst sendes som en input, når denne komponent kaldes). Her er displaytekst bare et brugerdefineret navn, som jeg har givet. {element}er den konstant, der blev skabt, som igen indeholder div-elementet.

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/

Du kan også følge mig på twitter //twitter.com/adityasridhar18

Mit websted: //adityasridhar.com/

Andre relevante indlæg af mig

En hurtig guide til at hjælpe dig med at forstå og oprette Angular 6-apps

En hurtig introduktion til Vue.js