How to create a new React component (using Hooks) [2021 tutorial]

In this tutorial I will guide you through a very simple process of creating a new functional component in React.

Functional components, in other words Hooks are a great way how to quickly build your app.

They contain almost every single feature from class components, but the most important feature, state, is 100% there.

Table of contents:

  • A simple component
  • An advanced component
  • A component with state

A simple component

The most basic definition of a react component is as follows:

//MyComponent.js

import React from 'react';
export default () => {
    return <div />;
};

That’s is. There are two requirements:

  • in every single component file you need to do the “import React” statement
  • every single component needs to return something, either a html element, another react component or null

It was a very simple component. You can do a lot with it. But to make your code more readable, continue reading and we will get to “props“.

An advanced component

Firstly, there is no official thing as “advanced component”. It is just my personal way of naming code writing, that makes it more clear for other developers.

What I mean by that?

I mean sooner or later, you will want to pass some data into your component, like for example:

import React from ‘react’;

import React from 'react';

export default ({value, onChange, isRequired, placeholder}) => {
    return <input value={value} onChange={e => onChange(e.target.value)} required={isRequired} placeholder={placeholder} />;
};

This component contains a simple <input /> html element and a couple of props. Neat, isn’t it?

But, imagine you will get back to this component after a couple of months. Now you are going to be asking yourself what the heck is “value”.

Is it a string? Can it be null? What the heck is placeholder? Is it boolean?

And so on.

And this is why react provided a way to solve this issue. It’s called PropTypes.

With PropTypes you can mark for every single prop type:

  • it’s data type
  • mark it as optional or required

Let’s have a look at the example of the input with PropTypes:

import React from 'react';
import PropTypes from 'prop-types';

const MyComponent = ({value, onChange, isRequired, placeholder}) => {
    return <input value={value} onChange={e => onChange(e.target.value)} required={isRequired} placeholder={placeholder} />;
};

MyComponent.propTypes = {
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    isRequired: PropTypes.bool,
    placeholder: PropTypes.string,
};

MyComponent.defaultProps = {
    isRequired: false,
    placeholder: "",
};

A dozen useless lines added, aren’t they? Well, not quite.

So what happened there?

The 1st thing that we did was named the component by assigning it to a variable. You know, in order to assign PropTypes to your components, they can not be anonymous functions, they need to be assigned to a variable.

The 2nd thing that we did we added a new property propTypes onto our component. Be aware of the case, since this property is case sensitive and for example “MyComponent.Proptypes” or “MyComponent.PropTypes” will not work.

The 3rd thing we did we added a new property called “defaultProps” onto our component. Again be aware of the case, since “MyComponent.Defaultprops” or “MyComponent.DefaultProps” will not work either.

PropTypes work only in development version of your react bundle. They are stripped away in production so you needn’t to worry about them making your bundle larger. (only in development 😁 ).

A component with state

Now, we have our component react and we need to add state. And this is what makes hooks hooks. A state in functional components.

So, let’s add a bit of state into our component:

import React, {useState} from 'react';
import PropTypes from 'prop-types';

const MyComponent = ({value, onChange, isRequired, placeholder}) => {
    const [isActive, setIsActive] = useState(false);
    
    return (
        <input
            value={value}
            onChange={e => onChange(e.target.value)}
            className={isActive ? "active" : "inactive"} 
            onBlur={() => setIsActive(false)} 
            onFocus={() => setIsActive(true)}
            required={isRequired} 
            placeholder={placeholder}
        />
    );
};

MyComponent.propTypes = {
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    isRequired: PropTypes.bool,
    placeholder: PropTypes.string,
};

MyComponent.defaultProps = {
    isRequired: false,
    placeholder: "",
};

What have happened there?

Two changes:

  • a new import {useState}
  • a new declaration const [isActive, setIsActive] = useState(false);

Only those two changes added a state into our component.

Easy right? 😉

Wrapping up

In this tutorial I walked you through how to create a simple react component using hooks.

I also showed you how you can make your component more readable to future you as well as to your colleagues.

And lastly, I showed you how you can use state in react component.

Hope everything is clear now and you can get to coding!

Until next time,

Yours in coding,

Ivan

Sources:

Leave a comment

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