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!