Here’s an example:

class greeting extends React.Component { 
  // ...
}
Copy the code

If you try to render, React will ignore the above and you’ll get a warning:

Warning: The tag <greeting> is unrecognized in this browser. 
If you meant to render a React component, 
start its name with an uppercase letter.
Copy the code

A bigger problem is that when you name your component button or IMG, React will ignore your component and render a native HTML button or IMG

Notice that there is no “My Awesome Button” rendered, React renders an empty HTML Button element. React won’t warn you in this case.

2. Use single quotation marks instead of back quotation marks

Using inverted quotation marks (‘… ‘) creates strings with single quotes (‘… ‘) creates different strings.

On most keyboards, you can use the key above the Tab key to enter the backquote (‘) character.

When we need to include dynamic expressions in the string, we create a string using backquotes (no string concatenation is required).

'This is a string template literal, can contain expressions'' This is just a string, can't contain expressions here 'Copy the code

Suppose you want a string that displays the current Time: “Time is…”

// Current time const time = new Date().tolocaletimeString (); // When using regular strings (single or double quotes), // you need to use string concatenation: 'Time is' + Time // When using backquotes, // you can use ${} to insert the Time 'Time is ${Time} 'into the stringCopy the code

Alternatively, when using string text (backquotes), you can create a string that spans multiple lines:

const template = `I

CAN

SPAN

Multiple Lines`;
Copy the code

You can’t do this with regular strings

Use 3.React.PropTypes

The PropTypes object has been removed from React. It used to work as React.PropTypes, but you can’t use it anymore.

Now use it like this:

1. Add new prop-types package to your project: NPM install prop-types 2. Import package: 'import PropTypes from 'prop-types''Copy the code

Then you can use it. For example: PropTypes. String

If you use React.PropTypes incorrectly, you will get the following error: TypeError: Cannot read property ‘string’ of undefined

4. Do not use the version the tutorial is using

When you see a tutorial or video and do a DEMO, make sure you are using the correct package or tool version. In general, using the latest version of each tool is a safe choice, but if the tutorial is a little old, you may run into some version issues.

For security purposes, it is recommended to use the same main version as the tutorial. For example, if the tutorial uses React.js 16, it is not recommended to use react.js 15

This is important for Node.js, as you may face major problems with older versions of Node.js. For example, if you follow some tutorial and they use Object.values and you use Node.js 6.x, this method doesn’t exist and you need to update it to Node.js 7.x

5. Confusedfunctionandclass

Can you tell me what’s wrong with the following code?

class Numbers extends React.Component { 
  const arrayOfNumbers = _.range(1, 10);
  // ...
}
Copy the code

The code above is invalid because you are not free to do anything inside the body of the JavaScript class. You can only define methods and properties with a limited syntax.

This is a bit confusing, because the {} used in class syntax looks like a normal block scope, but it’s not.

In a function-based component, you are free to do anything:

// Can do anything const Number = (props) => {const arrayOfNumbers = _. Range (1, 10); / /... };Copy the code

6. Pass numbers as strings

You can pass a prop value using a string:

<Greeting name="World" />
Copy the code

If you need to pass values, do not use strings:

// Do not <Greeting Counter ="7" /> instead, you need to use curly braces to enclose the values you want to pass. Javascript // Do this <Greeting Counter ={7} />Copy the code

Using {7} in the Greeting component, this.props. Counter will get a numeric 7 that is safe for math operations. If you think of it as a seven, and you think of it as a number, you might get unexpected results, you know.

7. Forgetting to create environment variables

Some projects rely on the presence of shell environment variables to start. If you run these projects without the environment variables, they will try to use undefined values for them and may give you some mysterious errors.

For example, if a project connects to a MongoDB database, it might use an environment variable like process.env.mongo_uri to connect to it. This allows projects to use different MongoDB instances in different environments.

To run a project connected to MongoDB locally, you must export a MONGO_URI environment variable first. For example, if you have a local MongoDB running on port 27017, you need to do this before running the project:

export MONGO_URI = "mongodb://localhost:27017/mydb"
Copy the code

You can use grep to look at the project source code to find out what environment variables it needs to work properly.

8. Confuse curly braces {} with parentheses ()

Can’t do that

return { 
  something();
};
Copy the code

Should be like this

return ( something(); ) ;Copy the code

The first will try to return an object, while the second will call something() correctly and return what the function returned

Since everything in JSX is converted to a function call, this applies when any JSX is returned

This problem is also common in phrasal methods of arrow functions

Can’t do that

const Greeting = () => { 
  <div> 
    Hello World 
  </div>
};
Copy the code

Should be like this

const Greeting = () => ( 
  <div> 
    Hello World 
  </div>
);
Copy the code

9. Wrap objects without parentheses

The curly braces and parenthesis problem above can also be confusing when you want to create a short arrow function that returns a normal object

Don’t be so

const myAction = () => { type: 'DO_THIS' };
Copy the code

Need such

const myAction = () => ({ type: 'DO_THIS'});
Copy the code

MyAction does not get a correct plain object without parentheses.

This is common in the setState method’s updater function because it needs to return an object. If you want to use the short arrow function syntax, you need to wrap the object in parentheses.

Don’t be so

this.setState(prevState => { answer: 42 });
Copy the code

Need such

this.setState(prevState => ({ answer: 42 }));
Copy the code

10.APIandpropsNot using the correct case

It’s react.ponent not react.ponent. It’s componentDidMount not componentDidMount. And ReactDOM is not a ReactDOM

Be aware of the API case you need. If you use incorrect uppercase letters, you may get an error that doesn’t clearly illustrate the problem.

When importing from React and react-dom, make sure you import the correct name, using the same name as the content you imported. ESLint can help you point out inaccuracies.

This problem is also common when accessing component props:

<Greeting userName="Max" /> // Inside the component, you need props. UserNameCopy the code

If instead of props.UserName, you use props.UserName or props.UserName incorrectly, you get undefined. Be aware of this, or better yet, configure your ESLint to handle these issues for you.

11. ConfusedstateObject and instance properties

In a class component, you can define a component State object and then access it using the following methods:

class Greeting extends React.Component { state = { name: "World", }; render() { return `Hello ${this.state.name}`; }}Copy the code

So that will print “Hello World”

You can also define an instance property near defining state

class Greeting extends React.Component { user = { name: "World", }; render() { return `Hello ${this.user.name}`; }}Copy the code

This will also output “Hello World”.

The state property is a special property because React will manage it, you can only change it by setState, and React will React when you do it. However, all the other instance attributes you define do not affect the rendering algorithm. You can change this.user as needed in the example above, React does not trigger the rendering cycle

12. Confused<tag/>and</tag>

Do not misplace the/character in the closing tag. Admittedly, sometimes you can use
and others that require
.

In HTML, there’s something called self-closing tags, and these are tags that represent elements that don’t have any child nodes. For example, the IMG tag is a self-closing tag:

<img src="..." You don't need to use <img></img>Copy the code

A div tag can have child elements, so you would use the start and end tags:

<div> 
  Children here...
</div>
Copy the code

The same applies to the React component. If the component has child content, it might look like this:

<Greeting>Hello! </Greeting>Copy the code

If the component has no child elements, you can use a self-closing component

// Both methods are valid <Greeting></Greeting> <Greeting />Copy the code

The following use is invalid

// Error <Greeting><Greeting />Copy the code

If you put the/character wrong, you will get the following error:

Syntax error: Unterminated JSX contents
Copy the code

13. Unbound function scope

I ended up saving this one because it’s a big question and a very common question.

You can define class methods in the React component and then use them in the render method of the component. Such as:

class Greeting extends React.Component { whoIsThis() { console.dir(this); // "this" is the caller of whoIsThis return "World"; } render() { return `Hello ${this.whoIsThis()}`; } } ReactDOM.render(<Greeting />, mountNode);Copy the code

Inside the Render method, I call the whoIsThis() method with the this.whoisthis keyword, which refers to the component instance associated with the DOM element representing the component, the Greeting component

React internally ensures that the this in its class method refers to the component instance, but JavaScript doesn’t automatically bind to the component instance when you use a reference to the whoIsThis method.

The this printed on the console.dir line points to the component instance because we’re calling it from within the Render method. When you execute the code above, you should see the Greeting object in the console:

However, when you use the same method in a deferred execution channel, such as an event handler, the caller is no longer clear, and the console.dir line does not point to the component instance.

See the code and output below (after click)

In the code above, React calls the whoIsThis method when you click on the string, but it doesn’t give you access to the component instance inside. That’s why when we click on the string you get undefined. This is a problem if your class methods need to access things like this.props and this.state. It doesn’t work at all.

There are many solutions to this problem. You can wrap a method in an inline function or use a.bind call to force the method to remember its caller. For components that are not updated frequently, either is fine. You can also optimize the binding method by doing it in the constructor of the class instead of in the Render method. However, the best solution for this approach is to enable the ECMAScript class-Fields segment functionality via Babel (still phase 3) and use arrow functions only for the handler:

class Greeting extends React.Component { whoIsThis = () => { console.dir(this); } render() { return ( <div onClick={this.whoIsThis}> Hello World </div> ); }}Copy the code

Will work as expected:

That’s all for now. Thanks for reading.