Book Image

React Design Patterns and Best Practices

By : Michele Bertoli
Book Image

React Design Patterns and Best Practices

By: Michele Bertoli

Overview of this book

Taking a complete journey through the most valuable design patterns in React, this book demonstrates how to apply design patterns and best practices in real-life situations, whether that’s for new or already existing projects. It will help you to make your applications more flexible, perform better, and easier to maintain – giving your workflow a huge boost when it comes to speed without reducing quality. We’ll begin by understanding the internals of React before gradually moving on to writing clean and maintainable code. We’ll build components that are reusable across the application, structure applications, and create forms that actually work. Then we’ll style React components and optimize them to make applications faster and more responsive. Finally, we’ll write tests effectively and you’ll learn how to contribute to React and its ecosystem. By the end of the book, you’ll be saved from a lot of trial and error and developmental headaches, and you will be on the road to becoming a React expert.
Table of Contents (19 chapters)
React Design Patterns and Best Practices
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Function as Child


There is a pattern that is gaining consensus within the React community, called Function as Child.

It is widely used in the popular library react-motion, which we will see in Chapter 6Write Code for the Browser.

The main concept is that, instead of passing a child in the form of a component, we define a function that can receive parameters from the parent.

Let's see what it looks like:

const FunctionAsChild = ({ children }) => children() 
 
FunctionAsChild.propTypes = { 
  children: React.PropTypes.func.isRequired, 
} 

As you can see, FunctionAsChild is a component that has a children property defined as a function and, instead of being used as a JSX expression, it gets called.

The preceding component can be used in the following way:

<FunctionAsChild> 
  {() => <div>Hello, World!</div>} 
</FunctionAsChild> 

It is as simple as it looks: the children function is fired in the render method of the parent and...