https://i0.wp.com/cdn.idevie.com/wp-content/uploads/2015/12/React.js_logo.svg_.png?resize=250%2C250&ssl=1

React Components are a fantastic piece of the react framework. However, I remember when I was getting started with React, components confused me quite a bit. I had a pretty solid understanding of JavaScript and OOP but these React components drove me up a wall for a bit (they still do from time to time). After a bit of time, I feel comfortable enough now to be able to explain some basics about React components and hopefully it’ll help you out a bit.

What are React Components?

Simply put, React components are nothing more than JavaScript classes. At a higher level, a React Component is an abstraction. They are a way of splitting up your web UI into manageable, reusable, individual pieces. You can then reuse these pieces all over the place. That’s the beauty of components. The main benefit of react components is to think of each piece independently from each other instead of thinking of your entire UI as a whole. This way you can build your UI more like a Lego house rather than a house of cards.

How Do You Use Them?

The best way to explain how to use components is through example. Let’s say we have this HTML page:

<html>
  <div id="wrapper">
    <div id="header">
      <h1>Hello World!</h1>
    </div>
    <div id="content">
       <p>Some really fun content</p>
    </div>
    <div id="userInput">
        <input type="textbox" id="textInput"/>
        <button id="submit">Submit</button>
    </div>
  </div>
</html>

Really basic but provides a foundation for an easy way for us to visualize how we could break this page up into components. Do you see how?

Anatomy of a React Component

Components have a few things to them that make them components. Let’s take a look at the most important parts:

State

Each component has something known as state. Think of this as the components editable attributes. State changes throughout the life of a component. If we put this into context with something we know, we can think of a toggle switch. A toggle switch will change state from toggled to not toggled throughout it’s lifetime. This is very similar to how a component’s state is. State changes over time.

Props

Component are passed props which are very similar to state except for the fact that they do not change. Props are to be left unchanged as they are passed to the component from the parent/instantiation. Props are used to set attributes of a component that will not change throughout the life time of a component.

Lifecycle

For each component, we have something known as the component lifecycle. This is the chain of events that happens to each component upon loading a page. The chain looks like this:

See more here

Each part of the lifecycle has its own lifecycle methods (in green above) which will be called at their appropriate times. This gives us a lot of power and control over each component and what we want each one to do.

Examples of React Components

In our example, there are 3 obvious pieces to our UI:

  1. header
  2. content
  3. userInput

Let’s take a look at breaking down these components one by one. When you’re ready to start coding, take a minute first to look over this compilation of VS Code extensions for Full Stack developers that might be helpful!

Class Based React Components

For our header component, it’s pretty simple. This component doesn’t need any props or state as it’s as simple as adding our <h1> tag and “Hello World” text. To be more reusable, we’ll make it so that “Hello World” a prop instead:

import React, { Component } from 'react'

class Header extends Component {
  render() {
    const { heading } = this.props;
    return (
      <div>
        <h1>{ heading }</h1>
      </div>
    )
  }
}

export default Header

Pure React Components

Next, our content which will be very similar. For this component, I will show an example of a pure component. Pure components are just functions that return what a class based component’s render function would return. Pure components are usually rather simple view layer components:

import React, { Component } from 'react'

Content = (props) => {
    const { text } = props;
    return (
      <div>
        <p>{ text }</p>
      </div>
    )
}

export default Content

State and Constructor

Finally, our user input section which will also look similar (starting to see a pattern here?):

import React, { Component } from 'react'

class UserInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      submitted: false
    };
  }

  submit() {
    this.setState({submitted: !submitted});
  }

  render() {
    return (
      <div id="userInput">
        <p>Submitted: {this.state.submitted}</p>
        <input type="textbox" id="textInput"/>
        <button id="submit" onclick={this.submit}>Submit</button>
    </div>
    )
  }
}

export default UserInput

Let’s take a closer look at this component. It’s is a little more complex than the other two. This component has a constructor and state. It is important to keep in mind that when setting the state, we only directly set the state in the constructor. If we want to set the state anywhere else in the component, then we need to use setState. This is because react lumps in calls to setState together to increase performance. What this also means is that setState is asynchronous and cannot be relied on to be completed right away. However, each setState call will re-render our component, which is super handy. Below is our UserInput component again for convenience:

Overview

As you can see by each of these new components, we do a couple of things. First, we extend Component which is imported from React. Next we implement the render method. This method is required to create a component and should return one of the following:

  • React Elements
  • Arrays and fragments
  • Portals
  • String and numbers
  • Booleans or null
  • Read more here

Render is a pure function that should be free from side effects and should not alter state. It should return the same result each time it’s invoked.

Conclusion

React Components are a fantastic abstraction for building elegant UI’s. These components are reusable, individual pieces of a UI. This allows us to focus on each individual piece rather than the whole structure. Use React Components to build Lego houses rather than houses of card.

Stay up to date on my recent posts
Get the latest content first.
We respect your privacy.

Leave a Reply

Your email address will not be published. Required fields are marked *