Skip to content
theLoneCoder text logo

WHY HAVE FRIENDS WHEN YOU HAVE CODE

  • Home
  • JavaScript
    • React.js
    • Node.js
    • DOM
  • Other
    • Bash/Terminal
    • Resources and Reviews
  • About Me
  • Contact Me
  • Home
  • JavaScript
  • React.js
  • React Class Components | React Tutorial for Beginners
Creating class-based components

React Class Components | React Tutorial for Beginners

Posted on February 10, 2023March 21, 2023 By theLoneCoder 4 Comments on React Class Components | React Tutorial for Beginners
React.js

 

In this article you’ll learn how to create React class components. In the previous article in this series, we learned how to make functional components. Class components are similar, except they use JavaScript classes instead of functions.

KEEP UP WITH { theLoneCoder }
Thank you for subscribing.
Something went wrong.
I upload new articles and tutorials daily throughout the week, so stay updated! You'll receive new tutorials on React, Node, and more.
We hate spam. Your email address will not be sold or shared with anyone else.

NOTE: While class components are still valid in React, it is recommended to use functional components instead! Even the React docs on the Component class say so! However, it is still important to understand class components as a lot of code still uses them.

Prerequisite Knowledge

  • JavaScript classes and inheritance
  • Rules of JSX
  • ES6 import/export syntax

Steps to Creating a Class-based Component

  1. Create a component file
  2. Make a class that derives from React.Component
  3. Add a render method
  4. return JSX from the render method
  5. Export the component

1. Create a component file

While it is possible to create a React component in the same file as other components (for example, App.js) it is best to have each component live inside its own file.

The file should be named the same as your component, with the js or jsx extension. I prefer JSX because it makes it obvious that it is a React component file, but it’s up to personal preference.

For instance, if you are creating a component called ProductDisplay, the file should be named either ProductDisplay.js or ProductDisplay.jsx.

Component files should be created inside of your applications src folder. Some developers create a subdirectory inside of src called components to organize all the app’s components, but this is optional.

2. Make a class that derives from React.Component

Open your component file in any text editor (e.g., VS Code, Notepad, or Vim/Nano).

To create a class-based component, you need to create a class that is a subclass of React.Component. This makes it necessary to import the react library, to gain access to this superclass.

NOTE: I can’t possibly explain everything the Component class can do here. So for more information, check out the React docs!

For now, we won’t add a constructor to our component class. A constructor becomes necessary when you add features such as state and props, which we will cover in a later tutorial.

Following the ProductDisplay example, below is the code to create the component class.


// ProductDisplay.jsx

import React from 'react';

class ProductDisplay extends React.Component {

}

The class we just created is quite useless! In the next steps, we will make our component return JSX code that can be rendered.

3. Add a render method

In order to render a class-based component, the class needs to have a method called render. The render method tells the component what to do when it is called.

We will actually make our render method do something in the next step. Below is how to add a render method to the component class.


// ProductDisplay.jsx

import React from 'react';

class ProductDisplay extends React.Component {
	render() {
		// Do the rendering here. . .
	}
}

4. Return JSX from the render method

To make a component appear on the webpage when it is rendered, we need to return JSX markup from the render method in the component class.


// ProductDisplay.jsx
import React from 'react';

class ProductDisplay extends React.Component {
	render() {
		return (
			<div id='productDisplay'>
				<h2>Display Product Here!</h2>
			</div>
		);
	}
]

This component still isn’t very useful. A ProductDisplay should actually display a product, not just give a “Display Product Here!” message. For illustrative purposes, lets make this component more useful. Below, we have an object called product containing information for a particular product. Normally this object would be passed down from a parent component after being retrieved from a database, but we have not yet covered props or API calls.

Also, the below example is the most complex example we have seen! This is great practice on the rules of JSX.


// ProductDisplay.jsx
import React from 'react';

const product = {
	name: 'Tennis Shoes',
	inStock: true,
	price: 59.99
};

class ProductDisplay extends React.Component {
	render() {
		return (
			<div id='productDisplay'>
				<h2>{ product.name }</h2>
				<h3>
					style={{color: (product.inStock ? 'green' : 'red')}}
				>{ product.inStock || 'Not' } in Stock</h3>
				<h3>Price: { product.price }</h3>
			</div>
		);
	}
}

Export the component

Because a component lives inside its own file, if you want to use it inside another component (for example, the App component) you need to import it.

But the components in your application do not automatically have access to each other. To make ProductDisplay component available to the others, we need to export it.


// ProductDisplay.jsx
import React from 'react';

const product = {
	// Not shown here for brevity!
};

class ProductDisplay extends React.Component {
	// Not shown here for brevity!
}

export default ProductDisplay;

The only new line is export default ProductDisplay;. This line makes the component available to the rest of your application.

You could also use a named export (export ProductDisplay;) but a default export is more common.

To use the ProductDisplay component inside of App.js, for instance, you’ll need to import it.


// App.js
import React from 'react';
import ProductDisplay from './ProductDisplay';
// If ProductDisplay used a named export, the above line would be:
// import { ProductDisplay } from './ProductDisplay';

class App extends React.Component {
	render() {
		return (
			<div id='app'>
				<h1>Welcome to theLoneCoder Products!</h1>
				<ProductDisplay />
			</div>
		);
	}
}

You’ll notice that we use the ProductDisplay component like any other HTML/JSX element. We could add attributes, styles, or anything else you can add to a normal element.

NOTE: Remember how I said you may place the component file into a folder called components? If you do this, you’ll need to change the path in your import statement. The importing line in App.js would become: import ProductDisplay from './components/ProductDisplay';

In the next article, we’ll learn more about how to structure a React application, using parent and child components to build a component tree. Our first component tree will be simple, but it will become more complex and fully featured as we learn about state, props, and hooks later on in this series.

Check out these articles!

Tags: class-based components

Post navigation

❮ Previous Post: React Functional Components | React Tutorial for Beginners
Next Post: React File Structure | React Tutorial for Beginners ❯

You may also like

React.js
React: How to Change a Parent Component’s State from a Child Component
January 25, 2023
Differences between JSX and HTML
React.js
JSX vs. HTML: Key Differences that Every React Developer Should Know
January 13, 2023
React.js
5 Most Important React Skills to Get a Job
January 16, 2023
React Tutorial for Beginners Basic Rules of JSX
React.js
Basic Rules of JSX | React Tutorial for Beginners
February 3, 2023

4 thoughts on “React Class Components | React Tutorial for Beginners”

  1. Pingback: React Functional Components | React Tutorial for Beginners
  2. Pingback: React State: useState and setState | React Tutorial for Beginners
  3. Pingback: React Props in Functional and Class Components - theLoneCoder
  4. Pingback: What Are React Hooks? | React Tutorial for Beginners

Leave a Reply Cancel reply

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

  • YouTube
  • GitHub
  • CodePen
  • Twitter
Substack

Subscribe to theLoneCoder!

Get updates on all new tutorials and blog posts from theLoneCoder.

Thank you!

You have successfully joined our subscriber list.

Recent Posts

  • [FIXED!] apt upgrade: the following packages have been kept back
  • [FIXED!] ReactDOM Deprecation notice | ReactDOM.render vs. createRoot
  • How to Show and Hide React Components (Easy!)
  • How to Write Comments in React/JSX
  • The React useEffect Hook and How to Use it

Categories

  • Bash/Terminal
  • DOM
  • JavaScript
  • Node.js
  • Other
  • React.js
  • Resources and Reviews
  • Home
  • Privacy Policy
  • About Me
  • Contact Me
  • YouTube

Copyright © 2023 theLoneCoder.

Theme: Oceanly News Dark by ScriptsTown