React Functional Components Example
In this article, we will learn about React Functional components with example. They are just JavaScript functions. We can optionally receive an object of properties referred to as props and return HTML which describes UI. HTML is actually something known as JSX but for the sake of understanding from a beginner’s point of view call it HTML. So, The functional component is a JavaScript function that accepts an input of properties and returns HTML that describes the UI. Let’s see the example of creating functional component in react
We can create functional components in the JS file itself. To create a functional component you must follow the below syntax:
syntax:
function functionName(){
return(
JSX statements;
)
}
Ex:
function Greet(){
return(
<h2> Hello Everyone </h2>
)
}
In the above code, we have created the functional component and we name it called Greet.
Inside the component, we returned some h2 element content.
To render this functional component to see our output follow this syntax:
Syntax:
ReactDOM.render(
<functionName/>,
document.getElementById('HTMLIDname')
Ex:
ReactDOM.render(
<First/>,
document.getElementById('root')
When we create the react app, we have given the ID name root. So here we have also selected “root” Idname.
Output:
If you create a functional component in another JS file instead of making it in an index.js file then you need to export the functional component in that file and import it in an index file. For example, if you create a functional component in newfile “greet.js” you need to export it.
Exporting syntax:
export default functionName;
Ex: Here, We are exporting the greet component as a default export from greet.js.
export default Greet;
Then import it to your index.js file
import variableName from './functionName';
Ex: Here, we have to import the greet file from “./greet”
import Greet from './greet';
Create a functional component using Es6
syntax:
const greet = () =>{
return(
Statement;
)}
This syntax looks more concise than the previous approach. Syntax wise it also has additional advantages which we will discover as we proceed with the course. If you are new to the arrow function please get a basic understanding of how they work as we will be using the lot.
Conclusion
But we can’t do many things using functional components so we can do everything with the class component. The class component is mostly created by the developers. A functional component is used to solve small problems.