Tutorial

Class Component Overview in React

Published on May 9, 2017
author

Matthew Garcia

Class Component Overview in React

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 our products

About the authors
Default avatar
Matthew Garcia

author

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.

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!

Become a contributor for community

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

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.