Open In App

How to create Functional Components in React ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To create a functional component in React, you define a JavaScript function that returns JSX. These components are stateless and rely on props for data input. Functional components are concise, easy to read, and can utilize React Hooks for managing state and side effects, making them a fundamental building block for React applications.

Prerequisites:

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app my-app

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd my-app

Project Structure:

Screenshot-2024-01-30-110533

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: Implementation to create a functional component.

Javascript




//App.js
 
import React from "react";
 
// This is the functional component
that will be added to the application
function GeeksforGeeks() {
    return (
        <div>
            <h1>
                GeeksforGeeks
            </h1>
            <p>
                GeeksforGeeks is a computer
                science portal for geeks.
            </p>
        </div>
    );
}
 
export default GeeksforGeeks;


Output:

Screenshot-2024-01-27-180313

Example 2: Implemenattion to show how to add a functional component in our application with a custom input by changing the contents of the header in the App.js file.

Javascript




//geeksforgeeks.js
 
import React from "react";
 
/* This is the functional component that will be
added to the application with custom input */
 
function GeeksforGeeks(props) {
    return (
        <div>
            <h1>
                {props.name}
            </h1>
        </div>
    );
}
 
export default GeeksforGeeks;


Javascript




// App.js
 
import GeeksforGeeks from "./components/geeksforgeeks";
import "./styles.css";
 
export default function App() {
    return (
        <div className="App">
 
            // Creating custom JSX tags
               with different inputs
 
            <GeeksforGeeks name="GeeksforGeeks" />
            <GeeksforGeeks name="A computer science" />
            <GeeksforGeeks name="portal" />
            <GeeksforGeeks name="for geeks" />
        </div>
    );
}


Output:

Screenshot-2024-01-27-181855

Step to run the application: Now to run the above code open the terminal and type the following command.

npm start


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads