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 (Render) something (E.g: a bootstrap Navbar, a dropdown list, a model, a dynamic form, image gallery, subscribe form, almost everything can be designed and coded as a React Component).

// as a function 
function NavBar(props){
    return (<nav className="navbar navbar-light bg-light">
              <a className="navbar-brand" href="#">Navbar</a>
           </nav>);
}

//or as a class 
import React from 'react';
class Navbar extends React.Component{
    render(){
        return (<nav className="navbar navbar-light bg-light">
              <a className="navbar-brand" href="#">Navbar</a>
           </nav>);
    }
}

Using a Component

Once the component declaration is finished you can reference it using tags like this:

import React from "react";
import { render } from "react-dom";

//here you tell react to put <NavBar /> inside the #myApp DOM element 
render(
  <NavBar />,
  document.querySelector("#myApp")
);

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 as we do in HTML tags.

<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.

let menu = [
    {label: 'Home', url: '/home'}
    {label: 'Contact Us', url: '/contact-us'}
];
<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.

The Component’s State

But what if my component changes over time? For example a <Clock /> component will need to update every second and show the current time. To do that we have the state.

What is this.state?

It’s a variable that you need to declare and initialize inside the component in a particular way. React.js will re-render the entire DOM every time you update that particular variable.

There’s a catch, though. The State is unmutable, which means the variable cannot be edited directly, so we have to update it using:

  • In a class component using the setState() function that receives the new State object (overriding the old one).
  • In a functional component using the useState hook and setter.

Updating the state on a functional component

//     pick a variable name.         initial value
//       ⬇                            ⬇
const [ error, setError ] = useState(null);
//               ⬆
//             pick the modifier name

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

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

Updating the state on a class-based component

// WRONG! Never update the state directly 
this.state.foo = "bar";

// CORRECT! Call the this.setState() function and pass the new state to it. 
const newState = {
    foo: "bar"
};
this.setState(newState);

// ALSO CORRECT! You can do it inline 
this.setState({
    foo: "bar"
});

Here is an example of the <Clock /> component we were just talking about:

Using a Function-based component (with hooks)

Using a Class-based component

But wait, should I use Function or Class?

We strongly recomend to use functions and hooks all the time (not Classes)

  • 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 declaration to the other without any pain! Here is a comparison about both types of components:

Component Simplicity

As a FunctionAs a Class
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.More complex – the class declaration needs to inherit from React.Component and it contains a lot more functionalities that lets 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

// using functions 
function MyComponent(){
    return Hello;
}
// or using arrow functions
const MyComponent = () => Hello;
// using classes
import React from 'react';
class MyComponent extends React.Component{
    render(){
        return Hello;
    }
}

Component State

As a FunctionAs a Class
Each variable should be declared using the useState Hook inside the functionThe state should be declared on the constructor and then use the function this.setState to update it.

class MyComponent{
    constructor(){
        super();
        python
            foo: "var"
       }
    }
}

Component Properties

As a FunctionAs a Class
Properties are received as the first function parameter like this:

function MyComponent(props){
        return Hello {props.name};
}
The properties are inside the class variable this.props, and you can reference it anywhere like this:

class MyComponent{
      render(){
          return Hello {this.props.name};
      }
}

Life-cycle Methods

As a FunctionAs a Class
Use the useEffect hook for the life cicle. More information here.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:

class MyComponent{
      constructor(){
          super();
          //initialize your state
          this.state = {}
      }
      componentDidMount(){ //do something to the state here }
      componentWillUnmount(){ //best place to remove listeners }
      static getDerivedStateFromProps(nextProps, prevState){ //return the updated state }
      //there are many more lifecycle methods
}