React Functional Components

In this tutorial, we will React Functional Components with examples.

  • A functional component is basically a JavaScript/ES6 arrow function that returns a React element (JSX). 
  • Naming convention: Functional Components always starts with a capital letter. 
  • Functional Component takes props as a parameter if necessary

Basic Functional Component

The functional component is basically a JavaScript/ES6 arrow function that returns a React element (JSX). 

In this example, we define a basic functional component called Greeting that renders a simple greeting message.

import React from 'react';

function Greeting() {
  return <h1>Hello, World!</h1>;
};

export default Greeting;

Let's rewrite the above functional component using the ES6 arrow function:

import React from 'react';

const Greeting = () => {
  return <h1>Hello, World!</h1>;
};

export default Greeting;

Functional Component with Props

Here, we define a functional component called Welcome that accepts a prop called name and renders a personalized welcome message.

import React from 'react';

const Welcome = (props) => {
  return <h1>Welcome, {props.name}!</h1>;
};

export default Welcome;

Next, use the Welcome functional component in the App component and pass the name property:

import Welcome from './components/Welcome'

function App() {

  return (
    <div>
        <Welcome name = "Ramesh"/>
    </div>
  )
}

export default App

Functional Component with JSX and JavaScript Expressions

In this example, we define a functional component called Counter that calculates and displays the count and its doubled value using JavaScript expressions within JSX.

import React, { useState } from 'react';

const ButtonCounter = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default ButtonCounter;

Functional Component with Event Handling

Here, we define a functional component called ButtonCounter that tracks a count state using the useState hook. It renders the count value and a button that increments the count when clicked, using an event handler function.

import React, { useState } from 'react';

const ButtonCounter = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default ButtonCounter;

Related Tutorials

Comments