React’s Five Fingers of Death. Master these Five concepts, then Master React.

By Sacha Greif

A few years ago, a friend of mine was touting how a framework called React would revolutionize Web development. In fact, at first I thought it was just another one-hit wonder. But in the time that followed, React became famous and became something to be reckoned with.

Maybe you’re in the same situation as me: you hear React all the time, but when you sit down to learn React, you have no idea what to do.

The good news is that I’ve summed it up for you here. React has only five core concepts.

Don’t get me wrong. I’m not going to turn you into a React expert, but if you’re planning or learning React, I can at least help you figure it out.

Here are the five core concepts:

  1. component
  2. JSX
  3. Props & State
  4. Component API
  5. Component type

Concept 1: What the React component does

The first thing you need to know about React is components. All the React code you write is basically one large component with many widgets.

So what exactly is a component? A good example is the HTML tag < SELECT >. The native dropdown tag not only contains borders, text, and drop-down arrows, it also controls its own open and close logic.

Now imagine that you need to build a <select> for your custom styles and behavior logic:

That’s what React does for you. The React component can output specific interface elements like native HTML tags, and it can also include code for some of the logic functions associated with the elements.

We now declare a React component using ES6’s Class syntax, which contains a render method that returns HTML. (You can also use function declarations, which we’ll talk about later.)

class MyComponent extends React.Component {
  render() {
    return <p>Hello World!<p>;
  }
}
Copy the code

Concept 2: What is JSX?

React: Write all the HTML and JS code together. React is implemented through a syntax extension called JSX (X stands for XML).

JSX may seem strange at first, but you’ll get used to it.

Yes, I know, it’s our tradition to keep HTML and JavaScript code as separate as possible. But it seems that forgetting this dogma is now the way to increase your front-end productivity.

Let’s take a few examples of JSX in action. For example, you can display JS variables in JSX with {} braces:

class MyComponent extends React.Component { render() { return <p>Today is: {new Date()}</p>; }}Copy the code

You don’t need front-end template tags anymore, you can use logic like ternary operators directly in JSX:

class MyComponent extends React.Component { render() { return <p>Hello {this.props.someVar ? 'World' : 'Kitty'}</p>; }}Copy the code

By the way, if you are not familiar with ES6, I recommend reading Ruan’s introduction to ECMAScript 6.

Concept 3: What is Props & State?

You might be wondering where this.props. SomeVar came from in the previous example.

If you know anything about HTML, you should be able to understand what the href attribute of the <a> tag means. Extending to React, properties are called props (short for properties). Components can interact with each other using Props.

class ParentComponent extends React.Component { render() { return <ChildComponent message="Hello World"/>; }} class ChildComponent extends React.Component {render() {return <p>And then I said, "{this.props. Message}" </p>; }}Copy the code

As such, data flows in React are one-way: data can only be passed from parent to child, not vice versa.

But a component can’t just accept data from its parent (and user input in the input, for example), so state comes in handy.

This example is so off the mark, I can’t help but quote an old poem to explain the difference between props and state:

People have joys and sorrows, the moon waxes and wanes.

We can think of a person’s genetic, gender, name (I know some things are mutable, but please don’t be too pushy), the size and weight of the moon as props, and emotions and cycles that can change over time as state.

Note that the state of a component can also be passed into a child component as the value of a child component prop. What you need to know is that in React the entire data flow flows downward, including routes, data layers, components, etc., from the entire application state and aggregated together.

In the build, we can modify state with a method called setState, which is normally called in the event-handling method:

class MyComponent extends React.Component { handleClick = (e) => { this.setState({clicked: true}); } render() { return <a href="#" onClick={this.handleClick}>Click me</a>; }}Copy the code

Most data in React applications is prop, and state is used only when the user enters content.

Note that in the code above, we use the automatic binding syntax. If you want to learn more about Handling Events, read the official documentation.

Concept 4: Component apis

We’ve already mentioned the Render and setState methods, both of which are included in the component API methods. Another useful method is constructor, where we typically initialize state and do some method binding.

In addition to these three methods, React provides a list of lifecycle functions that fire in a specific order. Don’t worry, though; you’ll only have a chance to use React when you learn more about it.

We won’t cover the React API here, because the main purpose of learning React is to learn how to program and how to build it, rather than to memorize boring API methods.

Concept 5: Component types

In React, we usually define a component as follows:

class MyComponent extends React.Component {
  render() {
    return <p>Hello World!<p>;
  }
}
Copy the code

There are many other methods we can declare on a component in Class, and more often than not we can write a functional component.

Similar to customizing a template tag, a functional component takes a props argument and returns specific HTML content, but you can still call some JS code in it:

const myComponent = props => {
  return <p>Hello {props.name}! Today is {new Date()}.</p>
}
Copy the code

Because often your components don’t need very complex interactions or extra methods, writing functionally makes your code much simpler.

Of course, you can’t use the setState method in such components, which means that functional components have no state, so they can also be called stateless components.

Of course, if you are new to React, you may have seen the following:

var Greeting = React.createClass({ render: function() { return <h1>Hello, {this.props.name}</h1>; }});Copy the code

Different component types have led to the concept of component roles. In practice, people have started to divide components into two roles: one that focuses on UI logic to show or hide content; The other focuses on data interaction, such as loading server-side data.

These two types of components are called container components and presentation components. Used to handle different business logic:

//presentational component

class CommentList extends React.Component {
  constructor(props) {
    super(props);
  }

  render() { 
    return <ul> {this.props.comments.map(renderComment)} </ul>;
  }

  renderComment({body, author}) {
    return <li>{body}—{author}</li>;
  }
}

//container component

class CommentListContainer extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }

  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: 'json',
      success: function(comments) {
        this.setState({comments: comments});
      }.bind(this)
    });
  }

  render() {
    return <CommentList comments={this.state.comments} />;
  }
}
Copy the code

This is kind of like the view/ Controller concept again. It’s just that there are different ways to build code, and while there are benefits to separating logic (such as separating business logic, better code reuse), you can also avoid it altogether.

High order component

Finally, we’ll touch a bit on the concept of higher-order components (often abbreviated as HOCs).

Think of it as a factory method, where you pass in a component and get a new component with more functionality returned by HOC. HOC cannot be called directly in the Render method. If you want to learn more, check out an example of react-Router in action.

Here’s another in-depth look at React advanced components.

conclusion

  • The React code is made up of components.
  • The component is written using JSX syntax extensions.
  • The data flow is always from parent to child, except that state can be changed by calling a method.
  • Components contain specific methods and lifecycle functions.
  • You can also use functions to declare stateless components that only have the Render method.
  • It is a good development practice to distinguish between components that handle UI and data logic.
  • Higher-order component functions can pass in a component and give it more functionality.

Believe it or not, we’ve covered 90% of what React developers use in their daily work. It may sound obscure, but React can always be reduced to functions and props.

React won’t be so scary once you understand it. Once you’ve mastered the React mode and can read its code at a glance, you’ll be able to install with confidence:

React is out

For more resources on React:

  • react-redux-links
  • awesome-react

If you have any good comments or thoughts about React, feel free to weigh in in the comments section.