React Class Components in a Nutshell

Creating a Class Component

Right click on the src file in your project directory and create a class component like so MyClassComp.jsx (Whatever the name is of your component. Usually when creating a component that is returning a React element then it will be jsx extension and then when you creating a file that just has pure JavaScript in it then you will use a JavaScript extension. The first thing you need to do is import React from react like so:

To create the class component, it’s going to be regular es6 so you will use the class keyword then the name of your component (Tip: give your components the same name as the file name so it’s easier to work with and so your project doesn’t become a mess). The component then needs extend the React.Component and then render the html. Lastly you will need to export your component like so:

Displaying the Class Component

To get the component to display, head over to App.js, import the component, remove all the default code between the header tags and insert your component like so:

Working with a Class Component Constructor and properties

Just like a regular class in JavaScript, you can add a constructor to the class component like so:

Working with Class Component Methods

You can also create methods on the class component, just remember that React can only return a single element so you will need to wrap both the button and the div that is used to display the name in a div wrapper like so:

Working with Class Component Variables

You can also create variables on the class component by creating the variable between the render and return:

Class Component State

You initialize state in the constructor of some variable or value. Then create a function that will update the state, you use the arrow function so that you don’t have to bind the function in constructor, and you need to then set the state of the variable or property by using setState:

Class Component Props

The information that you receive from a prop is read only information. With a class component props is something that is already available for us and you don’t have to drop in any arguments like how you would with a functional component. When you are using props on a class just to receive a value then you just do this.props on the fly, however if you want to initialize something with state or something in the constructor with a value from props on the component then props has to be passed in through the constructor.

Thank you for taking the time to read my article and hope you have found it useful.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store