Download Packt.react.design.patterns.and.Best.practices.1786464535 PDF

TitlePackt.react.design.patterns.and.Best.practices.1786464535
TagsComputer Programming Software Development Java Script Html Component Based Software Engineering
File Size3.8 MB
Total Pages308
Table of Contents
                            Cover
Copyright
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Table of Contents
Preface
Chapter 1: Everything You Should Know About React
	Declarative programming
	React elements
	Unlearning everything
	Common misconceptions
	Summary
Chapter 2: Clean Up Your Code
	JSX
		Babel
		Hello, World!
		DOM elements and React components
		Props
		Children
		Differences with HTML
			Attributes
			Style
			Root
			Spaces
			Boolean attributes
		Spread attributes
		JavaScript templating
		Common patterns
			Multi-line
			Multi-properties
			Conditionals
			Loops
			Control statements
			Sub-rendering
	ESLint
		Installation
		Configuration
		React plugin
		Airbnb configuration
	The basics of functional programming
		First-class objects
		Purity
		Immutability
		Currying
		Composition
		FP and user interfaces
	Summary
Chapter 3: Create Truly Reusable Components
	Creating classes
		The createClass factory
		Extending React.Component
		The main differences
			Props
			State
			Autobinding
		Stateless functional components
			Props and context
			The this keyword
			State
			Lifecycle
			Refs and event handlers
			No reference to component
			Optimization
	The state
		External libraries
		How it works
		Asynchronous
		React lumberjack
		Using the state
			Derivables
			The render method
	Prop types
		React Docgen
	Reusable components
	Living style guides
	Summary
Chapter 4: Compose All the Things
	Communication between components
		Children
	Container and Presentational pattern
	Mixins
	Higher-order Components
	Recompose
		Context
	Function as Child
	Summary
Chapter 5: Proper Data Fetching
	Data flow
		Child-parent communication (callbacks)
		Common parent
	Data fetching
	React-refetch
	Summary
Chapter 6: Write Code for the Browser
	Forms
		Uncontrolled components
		Controlled components
		JSON schema
	Events
	Refs
	Animations
		React motion
	Scalable Vector Graphics
	Summary
Chapter 7: Make Your Components Look Beautiful
	CSS in JS
	Inline styles
	Radium
	CSS Modules
		Webpack
		Setting up a project
		Locally scoped CSS
		Atomic CSS Modules
		React CSS Modules
	Styled Components
	Summary
Chapter 8: Server-Side Rendering for Fun and Profit
	Universal applications
	Reasons to implement Server-Side Rendering
		SEO
		A common code base
		Better performance
		Don't underestimate the complexity
	A basic example
	A data fetching example
	Next.js
	Summary
Chapter 9: Improve the Performance of Your Applications
	Reconciliation and keys
	Optimization techniques
		Should component update
		Stateless functional components
	Common solutions
		Why did you update?
		Creating functions inside the render method
		Constants props
		Refactoring and good design
	Tools and libraries
		Immutability
		Monitoring tools
		Babel plugins
	Summary
Chapter 10: About Testing and Debugging
	The benefits of testing
	Painless JavaScript testing with Jest
	Mocha is a flexible testing framework
	JavaScript testing utilities for React
	A real-world testing example
	React tree Snapshot Testing
	Code coverage tools
	Common testing solutions
		Testing Higher-Order Components
		The Page Object pattern
	React Dev Tools
	Error handling with React
	Summary
Chapter 11: Anti-Patterns to Be Avoided
	Initializing the state using props
	Mutating the state
	Using indexes as a key
	Spreading props on DOM elements
	Summary
Chapter 12: Next Steps
	Contributing to React
	Distributing your code
	Publishing a npm package
	Summary
Index
                        
Document Text Contents
Page 2

React Design Patterns and
Best Practices










Build modular applications that are easy to scale using the
most powerful components and design patterns that React
can offer you right now








Michele Bertoli




BIRMINGHAM - MUMBAI

Page 154

Write Code for the Browser

[ 141 ]

The callback we defined is called when the component gets mounted, and the element
parameter represents the DOM instance of the input. It is important to know that, when the
component gets unmounted, the same callback is called with a null parameter, to free the
memory. What we are doing in the callback is storing the reference of the element to be able
to use it in the future (for example, when the handleClick method is fired). Then we have
the button with its event handler. Running the preceding code in a browser will show the
form with the field and the button, and clicking on the button will focus the input field, as
expected.

As mentioned previously, in general, we should try to avoid using refs
because they force the code to be more imperative, and harder to read and
maintain.

The scenarios where we might need to use it without any other solutions are the ones where
we are integrating our components with other imperative libraries, such as jQuery.

It is important to know that when setting the ref callback on a non-native component (a
custom component that starts with an uppercase letter), the reference we receive as a
parameter of the callback is not a DOM node instance, but the instance of the component
itself. This is really powerful, because it gives us access to the internal instance of a child
component, but it is also dangerous and should be avoided.

To see an example of this solution, we are going to create two components:

The first one is a simple controlled input field, which exposes a reset function that
resets the value of the input itself to an empty string
The second component is a form with the previous input field, and a reset button
which fires the instance method when clicked

Let's start by creating the input:

class Input extends React.Component

We define a constructor with a default state (empty string), and bind the onChange method
we need to control the component, and the reset method, which represents the public API
of the component:

constructor(props) {
super(props)

this.state = {
value: '',
}

Page 155

Write Code for the Browser

[ 142 ]

this.reset = this.reset.bind(this)
this.handleChange = this.handleChange.bind(this)
}

The reset function is very simple, and just brings the state back to empty:

reset() {
this.setState({
value: '',
})
}

The handleChange is pretty simple as well, and it just keeps the state of the component in
sync with the current value of the input element:

handleChange({ target }) {
this.setState({
value: target.value,
})
}

Finally, inside the render method, we define our input field with its controlled value and
the event handler:

render() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
)
}

Now we are going to create the Reset component, which uses the preceding component,
and call its reset method when the button is clicked:

class Reset extends React.Component

Inside the constructor, we bind the event handler, as usual:

constructor(props) {
super(props)

this.handleClick = this.handleClick.bind(this)
}

Page 307

[ 294 ]

realworld example, Redux
reference 31
recompose library
about 98
context 101
reconciliation 11, 200, 201, 202, 204
Redux 61
Refs
about 139, 140, 141, 143
React motion 146
render method 200
ResponsiveMixin 94
reusable components 72, 73, 74, 76, 82

S
Scalable Vector Graphics (SVG) 147
Search Engine Optimization (SEO) 181
Semantic Versioning (SemVer) 289
server-side application
creating 184, 185, 189, 190
Server-Side Rendering (SSR)
about 180
better performance 183
code base 182
complexity 183, 184
implementing 181
Search Engine Optimization (SEO) 181
Shallow rendering 228
ShallowWrapper 243
single event handler 138
single global handler 139
Snapshot Testing 228, 253
solutions, re-rendering issues
about 209
components, no updation requires 209
constant props 215
functions, creating inside render method 212,

214

functions, creating render method 211
good design 217, 219, 221, 223
refactoring 217, 219, 220, 222
spread attributes
reference 28
spring function 146
state

about 61
asynchronous 62, 63
derivables 65
external libraries 61
initializing, props used 270, 271, 272, 273
mutating 273, 274, 276
React lumberjack 64
render method 66, 67
using 64, 65
working 61, 62
stateless function 50
stateless functional components
about 57, 58
context 58
event handlers 59
lifecycle 59
no reference to component 60
optimization 60
props 58
refs 59
state 59
this keyword 59
Storybook 87
Style Guide 87
style guide
about 76
checking 79
creating 76, 77, 78, 80
styled components 175
subtree 208
Synthetic Event 136

T
Tagged Template Literals 175
Test Driven Development (TDD) 230
testing solutions
about 257
Higher-Order Components 258
Page Object pattern 262, 264, 265, 266
testing
benefits 229, 230
TestUtils 228
Theming 177
TodoMVC example 245
TodoTextInput

Page 308

reference 245
tools 223

U
Uncontrolled Components 125
Unidirectional Data Flow 107

universal applications 180, 181
Universal Module Definition (UMD) 288

W
webkit 154
Webpack 163, 205, 288

Similer Documents