In this tutorial, you will learn about four design patterns that you can use when building an application with React.JS. A design pattern is an approach/technique for solving a problem in an understandable and efficient way. There are many different design patterns you can use with React, however, when you are getting started these are the ones I recommend using:
- Controlled Components
- Stateless Functions
- Conditional Rendering
- Rendering Child Components
As the name implies a controlled component is a component where React manages updating the DOM for you. Take this example:
In a controlled component, React manages the state for you, like so:
In this example, React manages the value. When the user adds some text the value is stored within a parameter managed by React, instead of the DOM.
If you are building a really simple component, then having all this background state-management can be overkill. This is where stateless components are handy. Stateless functions do not store state, or, have any event handlers you can hook into, like the componentWillReceiveProps(). When you create a stateless function you can only pass props into the render, like so:
Stateless functions are usually really simple components. As you can see from the simple example above, properties are directly rendered. When you come to view your code, it's very quick and easy to understand what a stateless component it doing.
When you start writing React components, you will frequently want to render some JSX based on state. If something is enabled, render component x, otherwise, render component y. You can achieve this through conditional rendering. You can add conditional rendering into a component using the curly brace syntax and some logic condition, like so:
This example shows how simple applying conditional rendering is. When the condition is true, e.g. 'isLoading' is set, then some loading JSX will be returned. Note the usage of the && which means when this is set, include this. The JSX will be skipped when the condition is false.
Rendering child components
React provides a useful property called 'children' that allow you to pass JSX into other components to be rendered. When dealing with a nested component, the parent decides the JSX and passes it down. Take:
To pass data into Notification you could write code, similar to:
In the example above, the text 'please login' is passed in-between the two notification tags. When you pass JSX into another component like this, React will add anything you pass in within a new property, called children. In the Notification component, you can render 'please login' use destructing to get children from the props and then render it. The 'Children' prop is a powerful approach for passing data into components without you having to write millions of props.
If you are interested in design patterns and you want to learn a little more, then I suggest you have a look at React Patterns.