Tutorial

Class Component Overview in React

Published on May 9, 2017
Default avatar

By Matthew Garcia

Class Component Overview in React

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Class syntax is one of the most common ways to define a React component. While more verbose than the functional syntax, it offers more control in the form of lifecycle hooks.

This guide assumes that Babel has been properly configured for React. If you are using create-react-app, this will already be the case.

Creating a class component

Creating a class component is pretty simple; just define a class that extends Component and has a render function.

// MyComponent.js
import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return (
      <div>This is my component.</div>
    );
  }
}

export default MyComponent;

From there, you can use it in any other component.

// MyOtherComponent.js
import React, { Component } from 'react';
import MyComponent from './MyComponent';

class MyOtherComponent extends Component {
  render() {
    return (
      <div>
        <div>This is my other component.</div>
        <MyComponent />
      </div>
    );
  }
}

export default MyOtherComponent;

You don’t have to define one component per file, but it’s probably a good idea.

Using props

As is, MyComponent isn’t terribly useful; it will always render the same thing. Luckily, React allows props to be passed to components with a syntax similar to HTML attributes.

<MyComponent myProp="This is passed as a prop." />

Props can then be accessed with this.props.

class MyComponent extends Component {
  render() {
    const {myProp} = this.props;
    return (
      <div>{myProp}</div>
    );
  }
}

A variable wrapped in brackets will be rendered as a string.

Using state

One of the benefits class components have over functional components is access to component state.

class MyComponent extends Component {
  render() {
    const {myState} = this.state || {};
    const message = `The current state is ${myState}.`;
    return (
      <div>{message}</div>
    );
  }
}

But since it wasn’t set anywhere, this.state will be null, so this example isn’t really useful. Which brings us to…

Using lifecycle hooks

Class components can define functions that will execute during the component’s lifecycle. There are a total of seven lifecycle methods: componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, and componentWillUnmount. For the sake of brevity, only one will be demonstrated.

class MyComponent extends Component {
  // Executes after the component is rendered for the first time
  componentDidMount() {
    this.setState({myState: 'Florida'});
  }

  render() {
    const {myState} = this.state || {};
    const message = `The current state is ${myState}.`;
    return (
      <div>{message}</div>
    );
  }
}

this.state should not be assigned directly. Use this.setState, instead.

this.setState cannot be used in render.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Matthew Garcia

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sharing one example of React Hook with class component: import React, { Component } from “react”; class Greeting extends Component { state = { text: “”, }; handleChange = (e) => { this.setState({ text: e.target.value }); }; render() { return <input value={this.state.text} onChange={this.handleChange} />; } } export default Greeting;

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel