Ideally, you can learn all about JavaScript and web development before delving into React. However, we can't do this. If you learn React after you have mastered all the knowledge of JavaScript, you will waste a lot of time. If you already have some experience in using JavaScript, all you need to learn before learning React is JavaScript knowledge that can be applied to the development of React applications. Those who master the following JavaScript knowledge points are enough for you to learn React.
- ES6 Class of
- Declare variable let/const
- Arrow function
- Destructuring assignment
- Map and filter
- ES6 Modular system
You'll use 20% of the JavaScript functionality 80% of the time, so in this tutorial, I'll help you learn all these features.
Explore the Create React App scaffold
Before learning React, we all use the create React app scaffold to create React applications. It has all the basic kits to run React.
https://reactjs.org/docs/create-a-new-react-app.html
npx create-react-app my-app cd my-app npm start
Then, when the process is complete, open Src / APP JS file, which will show us the only React class in the whole 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;
If you have never learned ES6 before, you will think that this kind of statement is a feature of React.
This is actually a new feature of ES6, which is why learning ES6 correctly can make you better understand React code.
We will start with ES6:
Class ES6
ES6 introduces class syntax, which is similar to object-oriented languages, such as Java or python. The basic classes in ES6 are as follows:
class Developer { // Constructor, when creating a new object (new), call // name is a parameter. You can define multiple parameters as needed constructor(name){ this.name = name; } // method hello(){ return 'Hello World! I am ' + this.name + ' and I am a web developer'; } }
Class is followed by the name of the class, which (a bit like a template) can be used to create a new object. This constructor is the constructor, which will be used when creating a new object with this class. Any arguments passed to the constructor are passed to the new object.
For example:
// Nathan will pass it to the constructor method, and finally this Name equals Nathan var nathan = new Developer('Nathan'); nathan.hello(); // Hello World! I am Nathan and I am a web developer
A class can define as many methods as necessary. In this case, we have a hello method that returns a string.
Class inheritance
One class can inherit from another, and the new object initialized from that class will have all the methods of both classes.
// ReactDeveloper inherits the Developer class class ReactDeveloper extends Developer { installReact(){ return 'installing React .. Done.'; } } // New objects are generated with subclasses var nathan = new ReactDeveloper('Nathan'); // The subclass object nathan will have all the methods of the subclass and the parent class nathan.hello(); // Hello World! I am Nathan and I am a web developer nathan.installReact(); // installing React .. Done.
A class that inherits from another class is usually called a subclass, and the inherited class is called a parent class or superclass.
A subclass can also override the methods defined in the parent class, which means that it will replace the parent method with the new method defined.
For example, let's override the hello function:
class ReactDeveloper extends Developer { installReact(){ return 'installing React .. Done.'; } // The Developer class also has a hello method, which is directly overridden here hello(){ return 'Hello World! I am ' + this.name + ' and I am a REACT developer'; } } var nathan = new ReactDeveloper('Nathan'); // What is called here will be the method after subclass coverage nathan.hello(); // Hello World! I am Nathan and I am a REACT developer
In this way, the hello method in the Developer class has been overridden.
Use in React
Now that we know about ES6 classes and inheritance, we can learn about Src / APP JS This is a react component, but it is actually just an ordinary ES6 class, which inherits the react component class imported from the react library.
// Import the react Component class and the Component class from the react library import React, { Component } from 'react'; // The components defined by ourselves inherit the Component class imported above class App extends Component { // class content render(){ return ( <h1>Hello React!</h1> ) } }
Because the App Component defined by ourselves inherits the Component class imported from the react library, we also have some methods of the Component class, such as render() method and this State these properties. However, as you may see later, classes are not the only way to define components. If you don't need state (a kind of state data) and Component life cycle methods, you can use functions instead of classes.
Declare variables using ES6 let and const
In the past, the var keyword was used to declare variables in JavaScript. ES6 introduced two new variable declarations: let and const. They are all the same and are used to declare variables. The difference is that const cannot change its value after declaration, while let can. Both declarations are local, which means that if you declare a let within the scope of a function, you cannot call it outside the function.
const name = "David"; let age = 28; var occupation = "Software Engineer";
Which one to use?
The rule of thumb is to declare variables using const by default. Later, when you write your application, you will realize that the value of const needs to be changed. At that time, you should think about reconstituting const into let. You should get used to using const or let.
When do we use it in React?
Each time we need a variable, look at the following example:
import React, { Component } from 'react'; class App extends Component { // class content render(){ // Here we use polymorph const greeting = 'Welcome to React'; return ( <h1>{greeting}</h1> ) } }
Since the greeting will not change throughout the application life cycle, we use const to define it here.
Arrow function
Arrow function is a new ES6 feature, which is almost widely used in modern code base because it keeps the code concise and readable.
This syntax allows us to write functions in a shorter syntax:
// regular function const testFunction = function() { // content.. } // arrow function const testFunction = () => { // content.. }
If you are an experienced JS developer, moving from a regular function syntax to an arrow syntax may be uncomfortable at first.
When I learned the arrow function, I used these two simple steps to rewrite my function:
- Delete function keyword
- Add arrow symbol after () = >
Parentheses are still used to pass parameters. If there is only one parameter, parentheses can be omitted.
// Two parameters const testFunction = (firstName, lastName) => { return firstName+' '+lastName; } // Parentheses can be omitted when a parameter const singleParam = firstName => { return firstName; }
Implicit return
If your arrow function has only one line, you can return the value directly without using the return keyword and curly braces {}
// Return directly without writing {} and return const testFunction = () => 'hello there.'; testFunction();
Use in React
Another way to create a React component is to use the arrow function.
Writing method of arrow function of React component:
const HelloWorld = (props) => { return <h1>{props.hello}</h1>; }
Equivalent to ES6 components
class HelloWorld extends Component { render() { return ( <h1>{props.hello}</h1>; ); } }
Using the arrow function in your React application makes the code more concise because it also removes the use of state from the component.
This type of component is called stateless functional component.
You will find this name in many React tutorials.
Deconstruction allocation of arrays and objects
Simply copy or deconstruct them into one of the most useful named objects in ES6.
A simple example:
const developer = { firstName: 'Nathan', lastName: 'Sebhastian', developer: true, age: 25, } //destructure developer object // A simple way to extract data from developer objects const { firstName, lastName } = developer; console.log(firstName); // returns 'Nathan' console.log(lastName); // returns 'Sebhastian' console.log(developer); // returns the object
As you can see, we assigned the firstName and lastName of the developer object to the new variables firstName and lastName
Now, what if you want to replace firstName with a new variable named name?
// : followed by variable alias const { firstName: name } = developer; console.log(name); // returns 'Nathan'
Deconstruction also applies to arrays, only if it uses indexes instead of object keys:
const numbers = [1,2,3,4,5]; const [one, two] = numbers; // one = 1, two = 2
You can skip some keys with:
const [one, two, , four] = numbers; // one = 1, two = 2, four = 4
Use in React
It mainly uses the deconstruction of state data, for example:
reactFunction = () => { const { name, email } = this.state; };
Or in a stateless component:
const HelloWorld = (props) => { return <h1>{props.hello}</h1>; }
We can simply deconstruct the parameters immediately:
const HelloWorld = ({ hello }) => { return <h1>{hello}</h1>; }
Deconstruct array useState Hook for React:
const [user, setUser] = useState('');
Map and filter
Although this tutorial focuses on ES6, you need to mention JavaScript array mapping and filter methods, as they may be one of the most commonly used ES5 functions when building React applications, especially processing data.
These two methods are more used to process data. For example, suppose you get results from a remote API and return a JSON data array:
const users = [ { name: 'Nathan', age: 25 }, { name: 'Jack', age: 30 }, { name: 'Joe', age: 28 }, ];
Then, we can present the list of items in React, as shown below:
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> ) } }
We can also filter the data in the rendering.
<ul> {users .filter(user => user.age > 26) .map(user => <li>{user.name}</li>) } </ul>
ES6 module system
The ES6 module system enables JavaScript to import and export files.
To explain this, let's look again at Src / APP JS code.
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;
In the first line of the code, we see the import statement:
import React, { Component } from 'react';
In the last line, we see the export default statement:
To understand these statements, let's first discuss module syntax.
A module is just a JavaScript file that uses the export keyword to export one or more values (which can be objects, functions, or variables).
First, create a file named util. Exe in the src directory JS new file
Then write a function in it, which is the default export
export default function times(x) { return x * x; }
One or more named exports
export function times(x) { return x * x; } export function plusTwo(number) { return number + 2; }
Then we can start from Src / APP JS import it
// From util Import from JS file import { times, plusTwo } from './util.js'; console.log(times(2)); console.log(plusTwo(3));
Each module can have multiple named exports, but only one default export.
You can import the default export without using curly braces and the corresponding export function name:
// in util.js export default function times(x) { return x * x; } // in app.js import k from './util.js'; console.log(k(4)); // returns 16
However, for named exports, you must import using curly braces and the exact name.
Alternatively, imports can use aliases to avoid using the same name for two different imports:
// 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';
Import from absolute name, such as:
import React from 'react';
The node under the root directory will be_ The modules directory performs a JavaScript check to get the corresponding package name.
Therefore, if you want to import a local file, don't forget to use the correct path.
Use in React
Obviously, we are in index JS to see the imported App components:
//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();
Please note: from When importing js extension, you can ignore the input and write of extension.
import App from './App';
summary
The biggest advantage of React is that it won't add any external abstraction layer on JavaScript like other web frameworks. That's why React has become very popular among JS developers. It just uses the best JavaScript to make the user interface easier and maintainable. In a React application, once you master the JavaScript knowledge mentioned above, you can confidently write React applications and become an excellent programmer.
Translated from: Nathan Sebhastian
Original text: https://dev.to/nsebhastian/javascript-basics-before-you-learn-react-38en