/  Technology   /  How to Create Functional Components in React JS
How to Create Functional Components in React JS

How to Create Functional Components in React JS

 

Components in React JS are classified into two i.e, Functional and Class based components. Functional components are some of the more common components that one will come across while working in React JS. Functional Components are 

Simply javaScript functions, which we can be creates by writing a javaScript function. 

These functions may or may not receive data as parameters. In the Functional Components,the value that returns in the function call is the JSX code which renders to the DOM tree. JSX stands for javaScript XML which is markup used in react.

Below is an example to create functional components in react js 

import React from 'react';
import ReactDOM from 'react-dom';
import Example from './App';
ReactDOM.render(
  <React.StrictMode>
    <Example />
  </React.StrictMode>,
  document.getElementById('root')
);

Filepath – src/index.js: Open your React project directory and modify the code in index.js file from the src folder.

The above code is to be present in index.js file which is the root or the parent file which gets rendered to the DOM trree. In index.js file we are importing react and ReactDOM from the react library, as it is required to import for rendering to the DOM. To be able to use any component we are firstly required to import the component to the parent file as done in the above code.

Filepath- src/App.js: Open your React project directory and modify the App.js file from src folder with the below-mentioned code:

Example.js 

 import React from 'react';
import ReactDOM from 'react-dom';
Const Example=()=>
{
  return <h1>Welcome to React Functional Components</h1>;
}
export default Example;

Here we are modifying the existing App.js file with a new file contents. In the above code we are importing react and ReactDom from the library. Then  creating a basic javaScript arrow function with a return statement. Each component created must be exported using the export default (functionName) 

Syntax for other components to be able to import and make this functional component reusable. 

Thus, this is how a functional component in react js would be created.

 

Leave a comment