A React component’s primary function is to classify the displayed view and connect it to the code that governs its actions. React 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 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.

Read More:   AI in mobile apps - how technology improves users' lives in 2022

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.

Read More:   Explore Most Marketable Healthcare App Ideas For Startups

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.

Rate this post
As a Senior Tech Enthusiast, I bring a decade of experience to the realm of tech writing, blending deep industry knowledge with a passion for storytelling. With expertise in software development to emerging tech trends like AI and IoT—my articles not only inform but also inspire. My journey in tech writing has been marked by a commitment to accuracy, clarity, and engaging storytelling, making me a trusted voice in the tech community.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      Success. Downloading...