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.
Functional Components are the simplest building blocks of a React application. They are JavaScript functions that return a React element.
Functional Components help keep our code clean, maintainable, and easy to understand. They are perfect for small, self-contained parts of our UI.
Let's create a simple Functional Component called Greeting.
function Greeting() {
return <h1>Hello, World!</h1>;
}In this example, Greeting is a Functional Component that renders a heading saying "Hello, World!".
Component names should be PascalCase (capitalize the first letter of each word).
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.
const element = <h1>Hello, World!</h1>;In the above example, the element variable holds a React element that describes an h1 heading.
Now, let's use the Greeting component in our main application.
function App() {
return (
<div>
<Greeting />
</div>
);
}In this example, we've created an App component that renders the Greeting component.
Always have an enclosing div or a single parent component for your components.
Functional Components can receive data (called props) from their parent components.
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.
Prop names should be in camelCase (lowercase the first letter of each word after the first).
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! 💻🎓🚀