image
author

Adam Davidson

Sr. Business Analyst

Reading Time: 4 minutes

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 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 which returning static text on the screen.

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

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 which followed by all react developers, we will write all our components inside this folder and then import them in App.js.

Lets create a file Person.js inside 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 passing its info as attributes. Person component will receive this info as props which is an object containing 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 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 which, 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 of 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 state: useState (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 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 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 changed or updated.

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

React hook for Effect: useEffect() (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 state variable resetCounter i.e true or false.

We passed resetCounter 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.

How useful was this post?

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Please do Rate Us and Share!

Related Blogs

  • author
    Kela Casey

    Tableau vs Power BI vs Qlik Sense | Comparison of Top 3 BI Tools

    Reading Time: 7 minutes Big data is a treasure trove for all types of companies. Every company deserves the best Big Data data analysis and visualization tool. In this post, we will try to provide you with as much detail as possible about the best...

  • author
    Thomas Wilfred

    React Native vs NativeScript: Which To Choose For Cross-Platform App Development

    Reading Time: 9 minutes Cross-platform app development is the process of building mobile apps from a single codebase for Android, Apple OS, and Windows instead of creating separate applications for specific operating systems. While this approach is cost-effective and saves tons of time, developers have...

  • author
    Adam Davidson

    Best Online Coding Editors For Beginners

    Reading Time: 6 minutes If you’re a budding web developer or a seasoned coder, you’ll need a code editor that can handle anything you throw at it. In reality, it’s possible that this is the most critical aspect of your toolkit. We wanted to set...

image

About The Author

Adam Davidson is the Sr. Business Analyst of Codersera, a leading freelance platform that caters to the mobile app development technology. Adam loves writing and researching on business leadership practices, start-up advice. He has a flair for writing and often shares his insights on various topics through his blogs.

Try our One-Week Risk Free Trial for Hiring a Coder

Know more Hire a Coder

Hire Top 1% Remote Developers, Free For The First Week

Connect with quality remote developers and code your ideas away.

X