4Geeks logo
4Geeks logo
About us

Learning library

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

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

Full-Stack Software Developer

Data Science and Machine Learning - 16 wks

Search from all Lessons

Social & live learning

The most efficient way to learn: Join a cohort with classmates just like you, live streams, impromptu coding sessions, live tutorials with real experts, and stay motivated.

← Back to Lessons

Continue learning for free about:

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 model, 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).

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

☝️ 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// here we tell React to put our main app component <Home /> inside the DOM element with id #myApp 5ReactDOM.render( 6 <Home />, 7 document.querySelector("#myApp") 8); 9 10// or we can use the Navbar component to display at the top of the Home component 11function Home(props){ 12 return ( 13 <div className="container-fluid"> //notice that in JSX we need to use the attribute name 'className instead of 'class' 14 <Navbar /> 15 <div> 16 ... The rest of Home's contents ... 17 </div> 18 </div> 19 ); 20} 21

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 2<Navbar foo="bar" foo2="bar2" /> 3

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 populated 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 of the state and reassigning it with the most current time every second. Like so:

☝️The following demo updates the current time on every second:

Click here to open demo in a new window

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 (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 2// 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 3constructor(){ 4 super(); 5 this.state = { 6 counter: 0 7 } 8} 9 10// from anywhere else in the class, we can reset the value of a state variable by passing an UPDATED object into the setState() method 11const newState = { 12 counter: 2 13}; 14this.setState(newState); 15 16// you can do the same operation inline as well 17this.setState({ 18 counter: 2 19}); 20// notice how above we have passed the entire new version of the state with the {} and the updated counter value within 21// 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:

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

☝️ 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 2// pick a variable name. initial value 3// ⬇ ⬇ 4const [ error, setError ] = useState(null); 5// ⬆ 6// pick the modifier name 7 8

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)

Click here to open demo in a new window

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 super 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 the 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 this component is supposed to display when placed on the website.

As a Class 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

1// using functions 2function MyComponent(){ 3 return Hello; 4} 5// or using arrow functions 6const MyComponent = () => Hello; 7 8// using classes 9import React from 'react'; 10class MyComponent extends React.Component{ 11 render(){ 12 return Hello; 13 } 14}

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.

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

Component Properties

As a Function :

Properties are received as the first function parameter like this:

1function MyComponent(props){ 2 return Hello {props.name}; 3}

As a Class :

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

1class MyComponent{ 2 render(){ 3 return Hello {this.props.name}; 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{ 2 constructor(){ 3 super(); 4 this.state = { //initialize your state } 5 } 6 componentDidMount(){ /* do something to the state here */ } 7 componentWillUnmount(){ /* best place to remove listeners */ } 8 static getDerivedStateFromProps(nextProps, prevState){ /* return the updated state */ } 9 //there are many more lifecycle methods 10 }

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