Things I Bookmarked When Learning React And ES6
Things I found important, strange or just interesting about react and es6 (from official tutorial). Article is for people who start learning react
Arrow Functions
Parenthesize the body of function to return an object literal expression:
Rest params and default params
Default Props
We can make them conditional when rendering, something like number || 0
or ternary operator or you can use static
Setting State
If we have functional component we need to convert it to a class and set initial state in constructor:
Never modify state directly, right way is to use setState
. If state updates may be asynchronous - we use setState
with callback
Setting state with setState
is shallow, so this.setState({comments})
leaves this.state.posts
intact, but completely replaces this.state.comments
.
Handling Events
Bind methods in constructor
Otherwise you will need to do callback in rendering, like:
In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
Passing Arguments to Event Handlers
Inside a loop it is common to want to pass an extra parameter to an event handler. For example, if id
is the row ID, either of the following would work:
Preventing Component from Rendering
In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.
Keys
Do not handle key attribute in extracted child component. Handle key in parent component
Keys Must Only Be Unique Among Siblings
Embedding map
in jsx
React router
How to pass props to component? You need to use render
instead component
property