- JavaScript Basics Before You Learn React
- Nathan Sebhastian
Writing in the front
In order not to waste your valuable time, I would like to start by stating that this article is intended for reading: For those of you who have never written React or who are new to React and don’t know much about the grammar of ES6, this is a basic introductory article. At the beginning, I didn’t plan to translate such a basic article. However, after reading the whole article, I remembered my confusion when I first learned React. There are so many ES6, how many do I need to master? For those of you eager to learn React code, this article gives you the basics to get started quickly. But later improvement, still need to consolidate the foundation of Javascript.
preface
Ideally, you’ll know all about JavaScript and Web development before you dive into React. Unfortunately, we live in an imperfect world, so munching through all the JavaScript before React will only make it harder for you. If you already have some JavaScript experience, all you need to learn before React is the actual JavaScript functionality used to develop React applications. Here are some JavaScript tips you should know before learning React:
ES6
类- use
let
/const
Declare a variable - Arrow function
- Deconstruction assignment
Map
和filter
ES6
Module system
This is 20% of the new JavaScript features you’ll use 80% of the time, so in this article, I’ll help you learn all of them.
createReact
Application exploration
A common way to start learning React is to run the create-react-app package, which sets up everything you need to run React. Once that’s done, open SRC/app.js to show us the only React class in the entire application:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
Copy the code
If you’ve never learned ES6 before, you might think that this class statement is a feature of React. This is actually a new feature of ES6, which is why learning ES6 properly will give you a better understanding of React code. We’ll start with ES6 classes.
ES6
The class of
ES6 introduces the Class syntax, similar to OO(object-oriented) languages such as Java or Python. The basic classes in ES6 are as follows:
class Developer {
constructor(name){
this.name = name;
}
hello(){
return 'Hello World! I am ' + this.name + ' and I am a web developer'; }}Copy the code
The class syntax is followed by an identifier (or a name) that can be used to create a new object. The constructor method is always called during object initialization. Any arguments passed to this object will be passed to the new object. Such as:
var nathan = new Developer('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a web developer
Copy the code
A class can define any method it wants; in this case, we define a Hello method that returns a string.
Class inheritance
Classes can extend the definition of another class, and new objects initialized from that class will have all the methods of both classes.
class ReactDeveloper extends Developer {
installReact(){
return 'installing React .. Done.'; }}var nathan = new ReactDeveloper('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a web developer
nathan.installReact(); // installing React .. Done.
Copy the code
Classes that inherit from another class are usually called child or sub classes, and classes that are being extended are called parent or super classes. A subclass can also override methods defined in its parent class, which means that it will replace the definition of the parent method with a new method it defines. For example, let’s override the hello function:
class ReactDeveloper extends Developer {
installReact(){
return 'installing React .. Done.';
}
hello(){
return 'Hello World! I am ' + this.name + ' and I am a REACT developer'; }}var nathan = new ReactDeveloper('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a REACT developer
Copy the code
So, we override the Hello method in the Developer class.
Used in React
Now that we know about ES6 classes and inheritance, we can understand the React class defined in SRC/app.js. This is a React Component, but it’s really just a plain ES6 class that inherits the React Component class definition imported from the React package.
import React, { Component } from 'react';
class App extends Component {
// class content
render(){
return (
<h1>Hello React!</h1>)}}Copy the code
This allows us to use the Render () method, JSX, this.state, and other methods. All of these definitions are in the Component class. But as we’ll see later, class is not the only way to define a React Component. If you don’t need states and other lifecycle methods, you can use functions.
useES6
In thelet
和 const
To declare variables
Because JavaScript’s var keyword is a variable declared globally, ES6 introduced two new variable declarations to solve this problem, let and const. They are used to declare variables. The difference is that const cannot change its value after being declared, whereas let can. Both declarations are local, which means that if you declare a let inside the function scope, it cannot be called outside the function.
const name = "David";
let age = 28;
var occupation = "Software Engineer";
Copy the code
Which one?
As a rule of thumb, the default is to declare variables using const. Later, when you write your application, you should refactor const to let when you realize that the value of const needs to change. Hopefully it will get you used to the new keywords, and you’ll start to realize that you need to use const or let patterns in your application.
What time will we be inReact
How about in?
When we need variables:
import React, { Component } from 'react';
class App extends Component {
// class content
render(){
const greeting = 'Welcome to React';
return (
<h1>{greeting}</h1>)}}Copy the code
The greeting does not change over the lifetime of the application, so we use const here
Arrow function
The arrow function is a new feature of ES6 that is almost universally used in modern code bases because it makes code concise and readable. It allows us to write functions with shorter syntax.
// regular function
const testFunction = function() {
// content..
}
// arrow function
const testFunction = (a)= > {
// content..
}
Copy the code
If you’re an experienced JS developer, switching from regular function syntax to arrow syntax can be uncomfortable. When I learned about arrow functions, I used these two simple steps to rewrite my functions:
- remove
function
The keyword - in
(a)
Followed by= >
Parentheses are still used to pass arguments, and if there is only one argument, the parentheses can be omitted.
const testFunction = (firstName, lastName) = > {
return firstName+' '+lastName;
}
const singleParam = firstName= > {
return firstName;
}
Copy the code
hiddenreturn
If the arrow function has only one line, it can return the value without the return keyword and curly braces.
const testFunction = (a)= > 'hello there.';
testFunction();
Copy the code
inReact
The use of
const HelloWorld = (props) = > {
return <h1>{props.hello}</h1>;
}
Copy the code
ES6 equivalent class component
class HelloWorld extends Component {
render() {
return (
<h1>{props.hello}</h1>;) ; }}Copy the code
Using the arrow feature in the React application makes the code simpler. But it also removes the use of state from components. Components of this type are called stateless functional components. You’ll see this name in many React tutorials.
Resolves assignments to arrays and objects
One of the most useful new syntaxes introduced in ES6 is that deconstructing assignments simply copies parts of an object or array and puts them into named variables. A simple example:
const developer = {
firstName: 'Nathan'.lastName: 'Sebhastian'.developer: true.age: 25,}//destructure developer object
const { firstName, lastName } = developer;
console.log(firstName); // returns 'Nathan'
console.log(lastName); // returns 'Sebhastian'
console.log(developer); // returns the object
Copy the code
As you can see, we assign firstName and lastName from the developer object to the new variables firstName and lastName. Now, what if you want to put firstName into a new variable named Name?
const { firstName:name } = developer;
console.log(name); // returns 'Nathan'
Copy the code
Destructuring also applies to arrays, using indexes instead of object keys:
const numbers = [1.2.3.4.5];
const [one, two] = numbers; // one = 1, two = 2
Copy the code
You can skip some subscripts in the deconstruction process by passing in:
const [one, two, , four] = numbers; // one = 1, two = 2, four = 4
Copy the code
inReact
The use of
The most common is to deconstruct state in a method:
reactFunction = (a)= > {
const { name, email } = this.state;
};
Copy the code
Or in a stateless function component, combined with the previous example:
const HelloWorld = (props) = > {
return <h1>{props.hello}</h1>;
}
Copy the code
We can immediately and simply deconstruct the parameters:
const HelloWorld = ({ hello }) = > {
return <h1>{hello}</h1>;
}
Copy the code
Map
和 filter
Although this article focuses on ES6, the JavaScript array Map and filter methods need to be mentioned because they are probably one of the most commonly used ES5 features when building React applications. Especially when it comes to processing data.
These two methods are used more often when dealing with data. For example, suppose we get an array that returns JSON data from an API result:
const users = [
{ name: 'Nathan'.age: 25 },
{ name: 'Jack'.age: 30 },
{ name: 'Joe'.age: 28},];Copy the code
We can then render the list of projects in React as follows:
import React, { Component } from 'react';
class App extends Component {
// class content
render(){
const users = [
{ name: 'Nathan'.age: 25 },
{ name: 'Jack'.age: 30 },
{ name: 'Joe'.age: 28},];return (
<ul>
{users
.map(user => <li>{user.name}</li>)}</ul>)}}Copy the code
We can also filter data in render
<ul>
{users
.filter(user => user.age > 26)
.map(user => <li>{user.name}</li>)
}
</ul>
Copy the code
ES6 module system
The ES6 module system enables JavaScript to import and export files. Let’s take a look at the SRC/app.js code again to explain this.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
Copy the code
In the first line of code we see the import statement:
import React, { Component } from 'react';
Copy the code
In the first line of code we see the export default statement:
export default App;
Copy the code
To understand these statements, let’s first discuss module syntax.
A module is simply a JavaScript file that exports one or more values (which can be objects, functions, or variables) using the export keyword. First, create a new file called util.js in the SRC directory
touch util.js
Copy the code
And then we’ll write a function inside that, using a default export
export default function times(x) {
return x * x;
}
Copy the code
Or multiple named exports
export function times(x) {
return x * x;
}
export function plusTwo(number) {
return number + 2;
}
Copy the code
We can then introduce it in SRC/app.js.
import { times, plusTwo } from './util.js';
console.log(times(2));
console.log(plusTwo(3));
Copy the code
Each module can have multiple named exports but only one default export. The default export can be imported without curly braces and the corresponding export function name:
// in util.js
export default function times(x) {
return x * x;
}
// in app.js
export k from './util.js';
console.log(k(4)); // returns 16
Copy the code
But for named exports, curly braces and the exact name import must be used. Alternatively, import can be aliased to avoid two different imports having the same name:
// in util.js
export function times(x) {
return x * x;
}
export function plusTwo(number) {
return number + 2;
}
// in app.js
import { times as multiplication, plusTwo as plus2 } from './util.js';
Copy the code
Introduce names directly like this:
import React from 'react';
Copy the code
JavaScript will be asked to check node_modules for the appropriate package name. Therefore, if you are importing local files, don’t forget to use the correct path.
Used in React
Obviously we’ve seen this in the SRC/app.js file, and then in the index.js file we’ve seen how the exported App component is rendered. Let’s ignore the serviceWorker part for now.
//index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
Copy the code
Notice how you import App from the./App directory and omit the.js extension. We can only omit file extensions when importing JavaScript files, but we must include extensions in other files, such as.css. We also imported another Node module, the React-dom, which enabled us to render the React component as an HTML element.
As for PWA, it’s a feature that makes the React application work offline, but since it’s disabled by default, there’s no need to learn it at first. After you’re confident enough to build the React user interface, it’s best to learn about PWA.
conclusion
The advantage of React is that it doesn’t add any external abstraction layer on top of JavaScript like other Web frameworks do. This is why React has become very popular with JS developers. It simply uses the best JavaScript to make building a user interface easier and maintainable. There really is more JavaScript than React Specix syntax in React apps, so once you have a better understanding of JavaScript – ES6 in particular – you can write React apps with confidence. But that doesn’t mean you have to know everything about JavaScript to start writing React applications. Write one now, and you’ll become a better developer as the opportunity comes along. Thanks for reading, I hope you learn something new 🙂
The last
Small volumes of Chrome debugging tips you didn’t know about are now available for pre-order.
Welcome to pay attention to the public account “front-end bully”, scan the code attention, there will be a lot of good things waiting for you ~