React JS is one of the most powerful and popular JavaScript libraries for building dynamic web applications. Whether you're just getting started or brushing up on the fundamentals, this post will walk you through how to build a functional component from scratchโwith real examples.
๐ง What Is a Functional Component?
A functional component is simply a JavaScript function that returns JSX. It's lightweight, easy to understand, and highly reusableโmaking it the perfect entry point for anyone learning React.
๐ป Example: Letโs Build One!
Hereโs a simple functional component called Greeting that accepts a name prop:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
And now, use this component in your main app file:
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';
ReactDOM.render(
<Greeting name="Ankur" />,
document.getElementById('root')
);
โ
Output:
Hello, Ankur!
This example demonstrates how props make components reusable and dynamic.
๐ง Bonus: Using ES6 Arrow Function
Prefer arrow functions? Hereโs a shorter version of the same component:
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
๐ How to Set Up a React Project
To run the code, create a React app using:
npx create-react-app my-react-app
cd my-react-app
npm start
Once your development server is running, add your components and test them in the browser!
๐ Final Thoughts
Functional components are the backbone of modern React development. Theyโre simple to understand, easy to scale, and pair perfectly with Hooks like useState and useEffect.
If you found this tutorial helpful, check out the full blog post for more insights and examples:
Top comments (2)
Nice, keep writing !
Functional components seriously made getting started with React so much easier for me.
Did you have a favorite Hook when you first started using them?