Complete Overview of React Functional Components

A React functional component is a straight JavaScript function that takes props and returns a React element. Writing functional components has been the traditional way of writing React components in advanced applications since the advent of React Hooks.

A React component’s primary function is to classify the displayed view and connect it to the code that governs its actions. React’s functional components reduce this to the most basic profile feasible: a function that accepts properties and returns a JSX definition. The function body contains all of the definitions needed for actions, and the class-related sections of object-oriented components are omitted.

How to create a simple functional component?

A functional component is pretty easy to define; as already mentioned, it is simply a function that returns a valid React element.

Let’s dive into the code, first of all, create a boilerplate for react using the command:

npx create-react-app react-functional-component
import React from 'react'
import './App.css';

function App() {
  return (
    <div className="App">
       <h1>My First Functional Component</h1>
    </div>
  );
}

export default App;

This is a very basic functional component that returns static text on the screen.

Note: You can also create Functional components using the ES6 arrow function.

Functional Component

React Functional Components Using Props

Functional components in React are pure javascript functions. It takes an object as an argument called props( stands for properties) and returns JSX.

Let’s understand this with the help of code.

Create a folder with name components inside src i.e /src/components. This is just a convention followed by all react developers, we will write all our components inside this folder and then import them in App.js.

Let's create a file Person.js inside the components folder:

# src/components/Person.js

import React from 'react';
import './Person.css'

const Person = (props) => {
    return (
        <div className="person">
            <h2>Name: {props.name}</h2>
            <h2>Age: {props.age}</h2>
        </div>
    );
};

export default Person;

And App.js looks like this:

# src/App.js

import React from 'react'
import './App.css';
import Person from "./components/Person";

function App() {
  return (
    <div className="App">
       <Person name="David" age={20} />
    </div>
  );
}

export default App;

What we are doing here is we are displaying personal info using props. We have included the Person component in App.js and passed its info as attributes. The person component will receive this info as props which is an object containing a name and age field inside it and we can use these details in the Person component wherever we want.

Event Handling: onClick and onChange

In this example, we will learn about event handlers in React for HTML elements like buttons and input elements. You can understand how to use a button and its onClick event, as well as how to identify and use various types of event handlers.

First, we will see an example of an onClick handler:

# src/App.js

import React from 'react';
import './App.css'

function App() => {

    const clickHandler = () => {
        alert('You are learning onClick Event')
    }

    return (
        <div className="alert">
            <button
                className="btn"
                onClick={clickHandler}
            >
                Show Alert
            </button>
        </div>
    );
};

export default App;

The above code displays a button with the text “Show Alert” which, when pressed, calls the clickHandler function which will then open the alert popup.

The onChange event handler is a prop that can be passed through the input elements of JSX. OnChange is used in React to manage user input in real-time. If you want to generate a React type, you must use this event to monitor the value of input elements.

Now let’s see an example onChange handler:

# src/App.js

import React from 'react'
import './App.css';

function App() {
    
    const onChangeHandler = (e) => {
        console.log(e.target.value);
    }
    
  return (
    <div className="App">
       <input type="text" onChange={onChangeHandler} />
    </div>
  );
}

export default App;

The above code showcases a single input field that, when typed in, passes its current value to the onChangeHandler function.

An onChange event handler i.e onChangeHandler in the above case returns a Synthetic Event object which comprises useful metadata such as the target input’s id, name, and current value.

We can access the target input’s value inside of the onChangeHandler by accessing the e.target.value. Hence, to log the name of the input field, we can log e.target.name

What are React Hooks? (Def and types only)

React hook for the state: state (explain with example)

React Hooks are functions that enable us to access React’s state and lifecycle properties from function components. Hooks enable us to better manipulate the state of our functional components without having to turn them into class components.

# src/App.js

import React, { useState } from 'react'
import './App.css';

function App() {

  const [counter, setCounter] = useState(0)

  const clickHandler = () => {
      const updatedCounter = counter + 1;
      setCounter(updatedCounter);
  }

  return (
    <div className="App">
        <div>Counter Value: {counter}</div>
        <button onClick={clickHandler}>
            Increase Counter
        </button>
    </div>
  );
}

export default App;

Let’s understand what we have written above, we are using a state variable called counter whose initial value is set as 0.
we have a button with the name “Increase Counter” which, when pressed, increases the current counter value by 1 and updates the current state using the setCounter method.

Updating the state will update the UI or re-render the component so we will see the updated counter value on the screen whenever the state changes or is updated.

Note: A state can be a string, number, array, object, or boolean whereas props is an object.

React hook for Effect: use effect() (explain with example)

Hooks are a brand-new feature in React 16.8. They allow you to use state and other React features without having to write a class. You may use the Effect Hook to conduct side effects in function components.

Let’s see an example, we are going to modify our above useState code to understand useEffect.

# src/App.js

import React, { useState, useEffect } from 'react'
import './App.css';

function App() {

  const [counter, setCounter] = useState(0);
  const [resetCounter, setResetCounter] = useState(false);

  const clickHandler = () => {
      setCounter(counter + 1);
  }

  const resetHandler = () => {
      setResetCounter(!resetCounter);
  }

  useEffect(() => {
      if(counter > 0){
          setCounter(0);
      }
  }, [resetCounter])

  return (
    <div className="App">
        <div>Counter Value: {counter}</div>
        <button onClick={clickHandler}>
            Increase Counter
        </button>
        <button onClick={resetHandler}>
            Reset Counter
        </button>
    </div>
  );
}

export default App;

As we can see above we added a reset counter button and passed a resetHandler function to onClick function. The job of resetHandler function is very simple, it just alters the value of the state variable resetCounter i.e true or false.

We passed the reset counter variable as a dependency of useEffect which means whenever resetCounter value changes or updates then it executes the code present inside it i.e it updates the value of the current counter as 0.
And we will see the counter value as 0 on the screen or UI.

FAQ's

What is the clickHandler function?

In React, the onClick handler allows you to call a function and perform an action when an element is clicked.

What is resetCounter Value?

The counter-reset property creates or resets one or more CSS counters. The counter-reset property is usually used together with the counter-increment property and the content property.

When is the onClick Button used?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form when you change certain content on the web page and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button