Function components in React.js are a way to create components using JavaScript functions. These components are simpler than class components and are often easier to read and test. Here’s a step-by-step guide to creating and using function components in React:
Creating a Function Component
A function component is a JavaScript function that returns a React element.
Create the Component File: Create a new file for your component, e.g., MyComponent.js.
// src/MyComponent.jsx
import React from 'react';
const MyComponent = () => {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
};
export default MyComponent;
Using the Component: Import and use this component in your main application file, e.g., App.js.
// src/App.jsx
import React from 'react';
import MyComponent from './MyComponent';
const App = () => {
return (
<div>
<MyComponent />
</div>
);
};
export default App;
Output will be: Hello, World!
Adding Props to a Function Component
Props are used to pass data from parent to child components.
Modify the Component to Accept Props:
// src/MyComponent.jsx
import React from 'react';
const MyComponent = (props) => {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
};
export default MyComponent;
Pass Props to the Component:
// src/App.jsx
import React from 'react';
import MyComponent from './MyComponent';
const App = () => {
return (
<div>
<MyComponent name="World" />
</div>
);
};
export default App;
Output will be: Hello, World!
Function Component – Interview Questions
Q 1: What is a function component?
Ans: A function component is a JavaScript function that returns JSX.
Q 2: Do function components support state?
Ans: Yes, using React Hooks like useState.
Q 3: What are the advantages of function components?
Ans: Simpler syntax, better performance, and easier testing.
Q 4: What is a hook in function components?
Ans: Hooks are functions that allow using state and lifecycle features in function components.
Q 5: Which is preferred today: function or class component?
Ans: Function components are preferred due to hooks and cleaner code.
Reactjs Function Component – Objective Questions (MCQs)
Q1. What is a React Functional Component?
Q2. Which React hook is commonly used in Functional Components for state?
Q3. Functional components were originally known as:
Q4. Which of the following is true about Functional Components?
Q5. Which syntax is correct for a Functional Component?