• Learning React. Js is easier than you think
  • By Samer Buna

Learning React. Js is easier than you might think

Learn the basics of React. Js with an article on Medium

Did you notice the six-pointed star hidden in the React logo? Just by the way… Last year I wrote a short book about learning React.js, about 100 pages long. This year, I’m going to challenge myself to summarize it into an essay and submit it to Medium.

This article isn’t about React or how you should learn React. This is an introduction to the basics of React. Js for those already familiar with JavaScript and DOM apis

* This article uses embedded jsComplete code snippets, so you’ll need a decent screen width for easy reading

All of the code below is for reference only. They are also purely examples for the purpose of expressing concepts. Most of them have better practices.

You can edit and execute any of the code snippets below. Use Ctrl+Enter to execute the code. In the bottom right corner of each paragraph is a link to edit or run the code in full-screen mode in jsComplete/ repL when clicked.


React is everything component

React is designed around the concept of reusable components. You define widgets and put them together to form larger components.

Regardless of size, all components are reusable, even across different projects.

In its simplest form, the React component is a plain JavaScript function:

Function Button (props) {return < Button type="submit">{props. Label}</ Button >; } // Render the Button component to the browser reactdom.render (<Button label="Save" />, mountNode)Copy the code

(Translator’s Note: The translation does not have this function, please visit the original text to use this function, the same as below)

The button tag in parentheses will be explained later. Don’t worry about them now. ReactDOM will also be explained later, but if you want to test this example and all the following examples, the above render function is what you need. React will take over and control the second parameter of reactdom.render, the target DOM element. In the jsComplete REPL, you can use the special variable mountNode.

Note for Example 1:

  • The component name starts with a capital letter, Button. We have to do this because we’re dealing with a mix of HTML elements and React elements. Lowercase names are reserved for HTML elements. In fact, name the React component “button” and you’ll see that ReactDOM ignores this function and simply renders it as a plain empty HTML button.

  • Each component receives a list of attributes, just like an HTML element. In React, this list is called a property. Although you can call a function whatever you want.

  • In the return output of the Button function component above, we have oddly written a section of code that looks like HTML. This isn’t actually JavaScript or HTML, and to be honest, it’s not even reac.js. However, it became so popular that it became the default in React applications. This is called JSX, and it’s a JavaScript extension. JSX is also a compromise! Go ahead and return other HTML elements in the function above to see how they are supported (for example, return a text input element).

2 What does JSX output?

Example 1 above can be written with pure React. Js without JSX as follows:

function Button (props) { return React.createElement( "button", { type: "submit" }, props.label ); } // To use a Button, you can do reactdom.render (react.createElement (Button, {label: "Save"), mountNode);Copy the code

In the React top-level API, the createElement function is the main function. This is one of the seven apis you need to learn. The React API is that small.

Just as DOM itself has a document.createElement function to create an element specified by the tag name, React’s createElement function is an advanced function with the same functionality as document.createElement. But it can also be used to create an element that represents the React component. When we use the button component in Example 2 above, we use the latter.

Unlike Document.createElement, React’s createElement takes a dynamic argument that represents the child elements of the created element after receiving the second argument. So createElement actually creates a tree.

Here is an example (low-level implementation, functional component) :

const InputForm = React.createElement( "form", { target: "_blank", action: "https://google.com/search" }, React.createElement("div", null, "Enter input and click Search"), React.createElement("input", { className: "big-input" }), React.createElement(Button, { label: "Search" }) ); // InputForm uses the Button component, so we need to do this: function Button (props) {return React. CreateElement (" Button ", {type: "submit" }, props.label ); } // Then we can use InputForm reactdom. render(InputForm, mountNode) directly with the.render method;Copy the code

A few things worth noting in the example above:

  • InputFormNot a React component; It’s just a ReactThe element. That’s why we can do thisReactDOM.renderIt is used directly in and can be called without it<InputForm />The reason why.
  • The react. createElement function takes multiple arguments after the first two. The argument list starting with the third argument forms the list of child items that create the element.
  • We can nestReact.createElementCall because it’s JavaScript.
  • When the element does not require an attribute, the second argument to the react. createElement can be empty or an empty object.
  • We can mix HTML elements in the React component. You can use HTML elements as built-in React components.
  • The React API tries to be like the DOM API, which is why we use it in the input element, rightclassNameInstead ofclassThe reason why. We all wish the React API had become part of the DOM API itself, because, you know, it’s so much better.

The code above is how the browser understands it when you introduce the React library. The browser does not handle any JSX business. However, we prefer to see and use HTML rather than those createElement calls (imagine building a website using document.createElement alone!). . That’s why JSX exists. Instead of calling React. CreateElement, we can use a very simple HTML-like syntax:

const InputForm = <form target="_blank" action="https://google.com/search"> <div>Enter input and click Search</div> <input className="big-input" name="q" /> <Button label="Search" /> </form>; // InputForm "still" uses the Button component, so we need to do the same. Function Button (props) {// This returns a DOM element. Return <button type="submit">{props. Label}</button>; } // Then we can use InputForm reactdom. render(InputForm, mountNode) directly with.render;Copy the code

Note a few things above:

  • This is not HTML code. For example, we can still use itclassNameInstead ofclass.
  • We’re still figuring out how to make the above JavaScript look like HTML. Let’s see how I added it at the end.

What we wrote above (example 4) is JSX. However, we will give the compiled version (example 3) to the browser. To do this, we need to use a preprocessor to convert the JSX version to the React.CreateElement version.

This is JSX. This is a compromise that allows us to write our React component in htML-like syntax, which is a good way to do it.

“Flux” is used as a rhyme in the head, but it is also a very popular application architecture popularized by Facebook. Best known for Redux, Flux and React fit well together.

JSX, which can be used alone, is not just for React.

You can use JSX anywhere in JavaScript

In JSX, you can use any JavaScript expression within a pair of curly braces.

const RandomValue = () => <div> { Math.floor(Math.random() * 100) } </div>; // Use: reactdom.render (<RandomValue />, mountNode);Copy the code

Any JavaScript expression can be placed directly in curly braces. This is equivalent to inserting the ${} template literals into JavaScript.

This is the only constraint in JSX: only expressions. For example, you can’t use if statements, but ternary expressions do.

JavaScript variables are also expressions, so when a component accepts a list of properties (excluding the RandomValue component, props is optional), you can use those properties in curly braces. We used the Button component above (example 1) like this.

JavaScript objects are also expressions. Sometimes we use JavaScript objects in curly braces, which looks like we’re using two curly braces, but there’s really only one object in curly braces. One use case is passing a CSS style object to a special style property in the response:

const ErrorDisplay = ({message}) =>
  <div style={ { color: 'red', backgroundColor: 'yellow' } }>
    {message}
  </div>;

// 使用
ReactDOM.render(
  <ErrorDisplay
    message="These aren't the droids you're looking for"
  />,
  mountNode
);
Copy the code

Note that I only deconstruct the information outside of the attribute parameters. This is just JavaScript. Also note that the style property above is a special property (again, it’s not HTML, it’s closer to the DOM API). We use an object as the value of the style property and this object defines the style just as we would with JavaScript (we can do this).

You can use the React element in JSX. Because this is also an expression (remember, a React element is just a function call) :

const MaybeError = ({errorMessage}) => <div> {errorMessage && <ErrorDisplay message={errorMessage} />} </div>; // MaybeError uses ErrorDisplay const ErrorDisplay = ({message}) => <div style={{color: 'red', backgroundColor: 'yellow' } }> {message} </div>; Reactdom.render (<MaybeError errorMessage={math.random () > 0.5? 'Not good' : ''} />, mountNode );Copy the code

The above MaybeError component will only display the ErrorDisplay component if an errorMessage is passed in or if there is an empty div. React considers {true}, {false} {undefined} and {null} valid elements and does not render anything.

We can also use all of JavaScript’s collection methods (Map, Reduce, filter, concat, etc.) in JSX. Because they return expressions as well:

const Doubler = ({value=[1, 2, 3]}) => <div> {value.map(e => e * 2)} </div>; Reactdom.render (<Doubler />, mountNode);Copy the code

Notice how I gave the default value for the value attribute above, because this is all just JavaScript. Notice that I’m just printing an array expression in div. React is perfectly fine. It only places each double value in a text node.

You can use JavaScript classes to write the React component

Simple function components are great for simple needs, but sometimes we need more. React also supports creating components using JavaScript classes. Here the Button component (in example 1) is written using class syntax.

class Button extends React.Component { render() { return <button>{this.props.label}</button>; Reactdom.render (<Button label="Save" />, mountNode);Copy the code

The syntax for the classes is pretty simple: define an extended React.componentclass (another top-level API you’ll need to learn about React). This class defines a single instance function, Render (), that returns a virtual DOM object. Each time we use a class-based Button component (e.g., through
),React instantiates the object from the class-based component and uses it in the DOM tree.

This is why in the example above we can render the output in JSX using this.props. Label, because each component has a special instance property called props, which allows all values to be instantiated when passed to the component.

Because we have an instance associated with a single use of a component, we can customize that instance. For example, we can construct it by using the regular JavaScript constructor:

class Button extends React.Component { constructor(props) { super(props); this.id = Date.now(); } render() { return <button id={this.id}>{this.props.label}</button>; <Button label="Save" />, mountNode);Copy the code

We can also define class prototypes and use them wherever we want, including inside the returned JSX output:

class Button extends React.Component { clickCounter = 0; handleClick = () => { console.log(`Clicked: ${++this.clickCounter}`); }; render() { return ( <button id={this.id} onClick={this.handleClick}> {this.props.label} </button> ); <Button label="Save" />, mountNode);Copy the code

Notice a few things in example 11 above

  • handleClickFunctions that use JavaScript are newclass-field syntaxSyntax. This is still Stage-2, but it’s the best choice (for many reasons) to access the component installation instance (thanks to the arrow function). However, you need to use a compiler like Babel to decode into Stage-2 (or just class field syntax) to make the above code work. JsComplete REPL has pre-compiled (pre-configured) functionality.
  • We defined it using the same class-field syntaxclickCounterInstance variable, which allows us to skip a class constructor call altogether.
  • When we specializehandleClickFunction as the react property value. We didn’t call it. We just pass tohandleClickFunction of theReference (reference). Calling functions at that level is one of the common mistakes with React
// Error: onClick={this.handleclick ()}Copy the code

5 Events in React: Two important differences

There are two very important differences between how we handle events in the React element and how the DOM API handles them:

  • All React element attributes (including events) are usedcamelCaseName, notlowercase. For example, isonClickRather thanonclick.
  • Instead of a string, we pass the actual JavaScript function reference to the event handler. For example, isonClick={handleClick}Rather thanonClick="handleClick".

React wraps DOM object events with its own objects to optimize event handling performance, but inside the event handler, we still have access to all accessible methods on DOM objects. React passes wrapped event objects to each calling function. For example, to prevent form submission from default submission, you can do this:

class Form extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form submitted');
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

// 使用
ReactDOM.render(<Form />, mountNode);
Copy the code

6 Every React component has a story: Part 1

The following applies only to class components (extension react.component.exe). Function components have a slightly different story.

  1. First, we define a template to create elements in the component.
  2. Then, we use React somewhere. For example, in therenderCall another component internally, or use it directlyReactDOM.render.
  3. Then React instantiates an object and sets itpropsAnd then we can go throughthis.propsAccess. These are the attributes we passed in in step 2.
  4. Because all of this is JavaScript,constructorThe method will be called (if defined). Here’s what we call the first one:Component lifecycle methods.
  5. React then calculates the rendered output method (the virtual DOM node).
  6. Because this is the first time React renders elements, React will communicate with the browser (meaning we use the DOM API) to display elements. This process is called mounting.
  7. React next calls another lifecycle function calledcomponentDidMount. We can use this approach by, for example, doing something in the DOM that we now know exists in the browser. Before this lifecycle approach, the DOM we used was virtual.
  8. The story of some components ends here, and others get uninstalled in the browser DOM for various reasons. In the latter case, another lifecycle method is called,componentWillUnmount.
  9. The state of any mounted element may change. The element’s parent may be re-rendered. In either case, mounted elements may receive a different set of attributes. That’s the magic of React, and that’s exactly what we need with React! Until then, to be honest, we don’t need React.
  10. The valence story continues, but before we do, we need to understand what I mean by this state.

7 The React component can be in the private state

The following applies only to class components. Did I mention that there are people who call component dumb presentational only?

The state class is a special field in any React class component. React detects (monitors) changes in the state of each component, but to be effective with React, we must change the state field via another API of React. This is another API we’ll learn about: this.setState:

class CounterButton extends React.Component {
  state = {
    clickCounter: 0,
    currentTimestamp: new Date(),
  };

  handleClick = () => {
    this.setState((prevState) => {
     return { clickCounter: prevState.clickCounter + 1 };
    });
  };

  componentDidMount() {
   setInterval(() => {
     this.setState({ currentTimestamp: new Date() })
    }, 1000);
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click</button>
        <p>Clicked: {this.state.clickCounter}</p>
        <p>Time: {this.state.currentTimestamp.toLocaleString()}</p>
      </div>
    );
  }
}

// 使用
ReactDOM.render(<CounterButton />, mountNode);
Copy the code

This is probably the most important example because this is how you’ll fully understand the basics of React. After this example, there are a few little things to learn, but from then on it’s mostly you and your JavaScript skills.

Let’s take a look at example 13, starting with the class. There are two, an initialized clickCounter object with an initial value of 0 and a currentTimestamp starting with new Date().

The other class is the handleClick function, where we pass an onClick event to the button element in the render method. The instance state of the component is modified using the handleClick method of setState. Be aware of that.

Another place we modify state is in an internal timer, starting with the internal componentDidMount lifecycle method. It calls once every second and executes another function call this.setstate.

In the render method, we use two properties on the state that have normal read syntax (no special API).

Now, notice that we update the status in two different ways:

  1. By passing in a function and then returning an object. We are inhandleClickLet’s do that inside the function.
  2. We do this in the interval callback by passing in a regular object.

Both methods are acceptable, but the first method is preferred when you read and write states simultaneously (we did). In interval callbacks, we only write to the state without reading it. Always use the first function as argument syntax when there is a problem. This is safer with race conditions, because setState is actually an asynchronous method.

How do we update our status? We return an object with the value we want to update. Notice that when we call setState, we all pass in a property from the state or none at all. This is perfectly fine because setState actually merges the existing state you passed through it (the function argument that returns the value), so not specifying a property when calling setState means we don’t want to change the property (but not remove it).

8 React will react

React gets its name from reactions to state changes (there is no reaction, but it is also in a schedule). Here’s a joke, React should be called Schedule!

However, when the state of any component is updated, what we see with the naked eye is the reaction to the update and the automatic reflection of the update in the browser DOM, if needed.

Consider the input to the render function as two:

  • Attributes passed in through the parent element
  • And an internal private state that can be updated at any time

When the input to the render function changes, the output may also change.

React keeps a history of renders, and when it sees a render different from the previous one, it calculates the difference and effectively translates it into the actual DOM operation performed in the DOM. (React keeps a record of the history of renders and when it sees that one render is different than the previous one, It’ll compute the difference between them and efficiently translate it into actual DOM operations that get executed in the DOM.)

9 React is your agent

You can think of React as the proxy we use to communicate with the browser. The current timestamp is displayed as an example. Instead of manually going to the browser every second and calling the DOM API to find and update p#timestamp elements, we just change the component’s state properties. React does the work that represents our communication with the browser. I believe this is the real reason why React is so popular; We just don’t like talking to Mr. Browser (and the many dialects of the DOM language it speaks), and React voluntarily proxies, for free!

10 Every React component has a story: Part 2

Now that we know the state of a component, when that state changes, let’s look at a few final concepts about the process.

  1. The component may need to be rerendered when its state is updated, or when its parent process decides to change the properties it passes to the component.
  2. If the latter happens, React calls another lifecycle method:componentWillReceiveProps.
  3. If the state object or the passed property changes, React has an important decision to make: Should the component be updated in the DOM? Is that why it calls another important lifecycle methodshouldComponentUpdateThe reason why. This method is a practical problem, so if you need to customize or optimize the rendering process yourself, you must answer this question by returning true or false.
  4. If there is no customshouldComponentUpdateReact’s default events work fine in most cases.
  5. First, another lifecycle method is called at this point:componentWillUpdate. React then evaluates the newly rendered output and compares it to the last rendered output.
  6. If the rendered output is the same as before, React doesn’t process it (no need to talk to Mr. Browser).
  7. If there are differences, React will communicate the differences to the browser, as we saw earlier.
  8. In any case, once an update has occurred, React will call the last lifecycle method in any way (even with the same output) :componentDidUpdate.

The life cycle method is the escape hatch. If you’re not doing anything special, you can create entire applications without them. They make it very easy to analyze what’s happening in your application and further optimize the performance of React updates.


Believe it or not, with what you’ve learned above (or some of it), you can start creating some interesting React applications. If you’re hungry for more, check out my Pluralsight’s React.js primer.

Thanks for reading. If you find this article helpful, please go to 💚. Check out my react.js and JavaScript articles for more.