React: thinking in components

React has many great features for developers that make the front end a pleasure to work in. Amongst the great features is the principle of components. These tiny chunks of usability are composed together to create entire applications piece by piece. In React, breaking down large interfaces into their individual functions brings a lego-like approach to developing.

An example

Resident advisor screenshot

I am using a small piece of Resident Advisor’s website to help demonstrate the concept of components. In React, components are very similar to a DOM tree in HTML. You are able to nest components within other components to create a waterfall structure. It is very common to have an App container component that will hold all the children components.

Let’s break down the card to see how the components would breakdown in React.

React component example

  • Card
    • Title
    • Image
    • Description
      • Comments
      • Podcast Title
      • Podcast Blurb

So, the card has 3 main sections: title, image, description. Within the description there are 3 more nested components.

React component example broken down

This composilibity of React components makes it possible to reuse all the individual pieces that you or anyone else has made. For example, if you create a button component you can reuse it in many different areas and pass it different specifications to alter the text, colour, or action.

Since components are small lego pieces that are are operating in isolation it is possible to change them individually without adversely impacting other components. React gives you the ability to to pass props and state to individual components that alter their appearance or behaviour. There are special tools that accompany React, such as Flux or Redux, to help deal with potentially complex prop and state situations. For now, it is only key to understand that components can have a prop or state that is mutable.

Furthermore, many applications are taking advantage of the nested architecture of React components by water-falling down state. The way I like to think of it is similar to CSS. In CSS, you can add a property to the body element and it will cascade down to all elements nested within the body as long as the nested elements don’t override the property. Similarly, in React, component state is often passed to the containing element and passed down to the nested components. This makes it easier to have a centralized system to keep track of component prop or state.

React redux state flow

Conclusion

Components are a great way to think when developing a highly detailed application. Keeping components as simple and basic as possible will help reduce complexity and tangled functions in the future.