Functional Components in React JS

beginner
10 min

Functional Components in React JS

Welcome to the Functional Components tutorial! In this lesson, we'll dive into one of the core concepts in React JS, a popular JavaScript library for building user interfaces.

🎯 What are Functional Components?

Functional Components are the simplest building blocks of a React application. They are JavaScript functions that return a React element.

Why Functional Components?

Functional Components help keep our code clean, maintainable, and easy to understand. They are perfect for small, self-contained parts of our UI.

📝 Creating a Functional Component

Let's create a simple Functional Component called Greeting.

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

In this example, Greeting is a Functional Component that renders a heading saying "Hello, World!".

💡 Pro Tip:

Component names should be PascalCase (capitalize the first letter of each word).

🎯 React Elements

When a Functional Component is called, it returns a React element. A React element is an object that describes what should appear on the screen.

jsx
const element = <h1>Hello, World!</h1>;

In the above example, the element variable holds a React element that describes an h1 heading.

📝 Using Functional Components in App

Now, let's use the Greeting component in our main application.

jsx
function App() { return ( <div> <Greeting /> </div> ); }

In this example, we've created an App component that renders the Greeting component.

💡 Pro Tip:

Always have an enclosing div or a single parent component for your components.

🎯 Props

Functional Components can receive data (called props) from their parent components.

jsx
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return ( <div> <Greeting name="John" /> </div> ); }

In this example, the Greeting component now accepts a name prop and displays it in the heading.

💡 Pro Tip:

Prop names should be in camelCase (lowercase the first letter of each word after the first).

🎯 Quiz

Question: How does a Functional Component describe what should appear on the screen?

A: By returning a JavaScript object B: By rendering HTML directly C: By calling a React library function

Correct: A

Explanation: A Functional Component returns a JavaScript object, called a React element, which describes what should appear on the screen.


Now that you've got the basics of Functional Components under your belt, let's dive into more advanced topics! Stay tuned for our next lesson on State and Lifecycle in React JS.

Happy coding! 💻🎓🚀