[React] import vs require, js vs jsx extension

Import VS Require

You may notice that some example code has “require” and some has “import”. What’s the difference?

The difference is ES5 vs ES6.
ES5:

var React = require('react');
var ReactProp = React.PropTypes;

ES6:

import React, { Component, PropTypes } from 'react';

Then how about .js and .jsx extensions?

.js vs .jsx Extensions

As of now, the extensions don’t matter.

Before Babel, .js extension was only used when files used standard JavaScript only.

With Babel now, we process both js and jsx with same Babel config, so it makes more sense to use .js extension for both.

Some people still prefer to use .jsx extension for React files because it helps some IDEs to edit and give “better” colors. However, you can configure that on your own so this is not a problem.

Ref: https://github.com/facebookincubator/create-react-app/issues/87#issuecomment-234627904

Conclusion
Use import for ES6 and require for ES5.
Use .js extension.

Advertisements

[React] Why you should use “prevState” in setState()

In stackoverflow or some other places that talk about React, I noticed that there were lots of code that did:

removeElement(index) {
  this.setState({
    data: this.state.data.filter((_, i) => i !== index)
  });
}

Or something similar by referencing this.state or this.props directly. However, this is discouraged (Source: https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)

React may batch the setState calls and thus, state may be asynchronously updated. Then, our code may fail to update.

Then how should we fix this code?

removeElement(index) {
  this.setState(function(prevState) {
    data: prevState.data.filter((_, i) => i !== index)
  });
}

[React] Auto Focus after render

I was building a dynamic form in a React component and encountered a problem. I couldn’t get the form to auto-focus on an input after submission.

I looked into ComponentDidUpdate() and/or ComponentDidMount(), but in the end, there was a simple solution to this.

class SomeForm extends Component {
	handleSubmit = (e) => {
		this.props.onSubmit(this.input.value);
		this.input.value = "";
		e.preventDefault();
	}

	render() {
		return (
			<form onSubmit={this.handleSubmit}>
				<input autoFocus type="text" ref={(input) => this.input = input} />
				<input type="submit" value="Submit" />
			</form>
		);
	}
}

Shown in the code above, by putting autoFocus attribute to true in the input tag, the problem was solved. When the form is rendered, it should automatically focus to the input.