Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.


Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons

LoginGet Started
← Back to Lessons
Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge
Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
Edit on Github

Creating React Components

In React.js Everything is a <Component />
Features of class components

In React.js Everything is a <Component />

React.js separates your code into little pieces called Components which can be created/defined as a class or as a function. Each component is like a smaller React app that has its own logic and has a final purpose, which is to display or render something (e.g: a bootstrap navbar, a dropdown list, a modal, a dynamic form, an image gallery, subscribe form), almost everything can be designed and coded as a React Component. To do that every React component needs to have a return statement that returns some JSX code (HTML + embedded JS).

1import React from 'react'; 2 3// a function component 4function NavBar(props){ 5 return (<nav className="navbar navbar-light bg-light"> 6 <a className="navbar-brand" href="#">Navbar</a> 7 </nav>); 8}
1import React from 'react'; 2 3// a class component 4class Navbar extends React.Component{ 5 render(){ 6 return (<nav className="navbar navbar-light bg-light"> 7 <a className="navbar-brand" href="#">Navbar</a> 8 </nav>); 9 } 10}

☝️ This is a class component. We strongly recommend you to use functional components and hooks instead because class components are legacy.

Using a Component

Once you have composed a component, you can display it using tags like this:

1import React from "react"; 2import ReactDOM from "react-dom"; 3 4// We can use the <Navbar /> component to display at the top of the Home component 5function Home(props){ 6 return ( 7 <div className="container-fluid"> // Notice that in JSX we need to use the attribute name 'className' instead of 'class' 8 <Navbar /> 9 <div> 10 ... The rest of Home's contents ... 11 </div> 12 </div> 13 ); 14} 15 16// Here we tell React to put our main app component <Home /> inside the DOM element with id #myApp 17ReactDOM.render( 18 <Home />, 19 document.querySelector("#myApp") 20);

The Component Props

Sometimes a component needs dynamic information to display. For example, we need our <Navbar /> component to show the list of available links and the brand’s logo. We can include that information within the call of the <Navbar /> component just the same way as we do in HTML tags.

1<Navbar foo="bar" foo2="bar2" />

In this example, we are passing an array of menu items and a logo URL to the NavBar component that we have just declared above.

1let menu = [ 2 {label: 'Home', url: '/home'}, 3 {label: 'Contact Us', url: '/contact-us'} 4]; 5<Navbar items={menu} logo="http://path/to/logo.png" />

Now, within the <Navbar /> we can use those values (which are delivered through the props variable) to render the information given.

And, lastly, you should tell React where to render that component into the DOM.

Click here to open demo in a new window

Features of class components

The Component’s State

We call class components in React stateful because they come with a global state object (shared within the same component only) which has the sole purpose of storing the data needed to render the component. One obvious use of the state object would be if, for example, we have a form with input fields that need to be filled by the user. The data entered by the user will need to be saved somewhere in order to be used. The state will be that place.

In another example, let's say that you are developing a <Clock /> component that has to print the current time every second. That means that our component will need to re-render every second.

In order for the state to keep a web page up-to-date, it is programmed to re-render the DOM every time it is modified. So you can probably already see how you can take advantage of this feature by keeping your current time inside the state and reassigning it to the most current time every second. Like so:

👇 The following demo updates the current time every second:

The state is always inside of the constructor() method of the class components and is expressed as a plain JS object literal.

The State Object is considered Immutable (it should not be changed directly)

When speaking about modifying the value of the state, you have to remember that the state should not be mutated directly. It should only be modified by calling the specially designated method this.setState(). In it, you will have to pass a new/updated state object that will replace the previous state values. For example:

1// A direct assignment of this.state is only allowed in the constructor method of your class; anywhere else it may cause an error in your stored data 2constructor(){ 3 super(); 4 this.state = { 5 counter: 0 6 } 7} 8 9// From anywhere else in the class, we can reset the value of a state variable by passing an UPDATED object into the setState() method 10const newState = { 11 counter: 2 12}; 13this.setState(newState); 14 15// You can do the same operation inline as well 16this.setState({ 17 counter: 2 18}); 19// Notice how above we have passed the entire new version of the state with the {} and the updated counter value within 20// Notice this new version will completely replace the old version of the state, erasing any other data that may have been in it

State updates happen in an asynchronous manner, and directly mutating the state creates an opportunity for values to be incorrectly updated and cause data inconsistencies in your web application.

The Component Constructor

As it was mentioned above, the place to initialize your component state is in the constructor method.

The constructor of each component gets called automatically very early in the application's runtime – even before your website has been mounted.

If you do not need to use the state, you do not need to explicitly implement a constructor method, and in some examples, you will see this method missing. However, if you will need to use the state, it is extremely important to initialize its values; otherwise on the first render your application is going to return your state variables as undefined.

You will also need to implement your constructor method if you will be using any props with the super(props) method. That allows you to inherit from the superclass React.Component of which every React class component is a subclass.

1class ClockComponent extends React.Component { 2 constructor(props){ 3 super(props); 4 // Here is a great place to define the first value your component state will have 5 this.state = { 6 currentTime: new Date() 7 }; 8 } 9}

Here is a complete React class-component template for reference:

1import React from 'react'; 2import ReactDOM from 'react-dom'; 3 4class Clock extends React.Component { 5 // The standard constructor method with props and this.state initialized 6 constructor(props) { 7 super(props); 8 this.state = {date: new Date()}; 9 } 10 11 // A React lifecycle method 12 componentDidMount() { 13 this.timerID = setInterval( 14 () => this.tick(), 15 1000 16 ); 17 } 18 19 // A React lifecycle method 20 componentWillUnmount() { 21 clearInterval(this.timerID); 22 } 23 24 // A custom method created by the developer to serve a purpose 25 tick() { 26 this.setState({ 27 date: new Date() 28 }); 29 } 30 31 // The standard render method with the component's return 32 render() { 33 // Here we can insert any JS code that needs to execute on every re-render and would be used in the return below, like dynamic variables or statements 34 return ( 35 <div> 36 <h1>Hello, world!</h1> 37 <h2>It is {}.</h2> 38 </div> 39 ); 40 } 41} 42 43ReactDOM.render( 44 <Clock />, 45 document.getElementById('root') 46);

☝️ This is a class component. We strongly recommend you use functional components and hooks instead because class components are legacy.

Features of function components

Functional components are simplified React components originally intended for presentational purposes. For that reason they are traditionally stateless: they have no state of their own. That allows them to be lighter, faster, and easier to write.

Functions' statelessness was addressed with React 16.8.0 which introduced the ever-so-popular React Hooks. Since then the useState hook allows us to reproduce state behavior in our functional components:

Updating the state of a functional component

1// pick a variable name initial value 2// ⬇ ⬇ 3const [ error, setError ] = useState(null); 4// ⬆ 5// pick the modifier name

For example, we can pick any variable and modifier like this:

1const [ size, setSize ] = useState(2); 2const [ color, setColor ] = useState("pink"); 3const [ anything, setAnything ] = useState(<any value>);

Using a Function-based component (with hooks)

But wait, should I use Function or Class?

So React Hooks effectively changed the nature of the original React functional components, and now both types of components are very similar in the things they can do. Because of that, we strongly encourage you to use functions and hooks as much as possible.

  • Functions are much simpler.
  • Your bundle (your entire website) size will be lighter and faster to download.
  • Eventually, classes will be deprecated.

You can switch from one type of declaration to the other without any pain! Here is a comparison of both types of components:

Component Simplicity

As a Function: Very simple declaration and usage. The only purpose of the function is to return an HTML with whatever the component is supposed to display when placed on the website.

As a Class: It is more complex, the class declaration needs to inherit from React.Component and contains a lot more functionalities that let the developer customize the component logic, like life-cycle methods and the state. Please consider that you can create as many additional class methods as you like.

Component Declaration

1import React from 'react'; 2 3// Using functions 4function MyComponent() { 5 return ( 6 <div> 7 <h1>Hello</h1> 8 </div> 9 ); 10} 11 12// Or using arrow functions 13const MyComponent = () => { 14 return ( 15 <div> 16 <h1>Hello</h1> 17 </div> 18 ); 19}; 20 21// Using classes 22class MyComponent extends React.Component { 23 render() { 24 return ( 25 <div> 26 <h1>Hello</h1> 27 </div> 28 ); 29 } 30}

Component State

As a Function:

Each variable should be declared using the useState Hook inside the function.

As a Class:

The state should be declared on the constructor and then use the function this.setState to update it.

1class MyComponent extends React.Component { 2 constructor() { 3 super(); 4 this.state = { 5 foo: "var" 6 }; 7 }

Component Properties

As a Function :

Properties are received as the first function parameter like this:

1function MyComponent(props){ 2 return <div>Hello {}</div>; 3}

As a Class :

The properties are inside the class variable this.props, and you can reference it anywhere like this:

1class MyComponent extends React.Component { 2 render() { 3 return <div>Hello {}</div>; 4 } 5}

Life-cycle Methods

As a Function:

Use the useEffect hook for the life cycle. More information here.

As a Class:

You have all the methods available, with these being the most important ones: Constructor, ComponentDidMount (or useEffect for Hooks), ComponentWillUnmount (or useEffect for Hooks), etc.

You can declare inside your component class those methods, and they will magically be called by React at the right time, just like this:

1class MyComponent extends React.Component { 2 constructor() { 3 super(); 4 this.state = { /* Initialize your state */ } 5 } 6 7 componentDidMount() { /* Do something to the state here */ } 8 9 componentWillUnmount() { /* Best place to remove listeners */ } 10 11 static getDerivedStateFromProps(nextProps, prevState) { /* Return the updated state */ } 12 13 // There are many more lifecycle methods

🔗 Here you can find more information about all the React JS lifecycle methods.