How To Create a React Component
n React, components are the building blocks of the user interface. Components allow you to split the UI into independent, reusable parts. There are two main types of React components:
Functional Components: These are simple JavaScript functions that return JSX (HTML-like syntax).
Class Components: These are ES6 classes that extend React.Component
and include a render
method.
Functional Components (Preferred)
Structure of a Functional Component
A functional component is essentially a JavaScript function that returns a React element (JSX) to be rendered on the page. Functional components are stateless by default but can manage state using React Hooks.
Example of a Basic Functional Component
Here’s how you create a simple functional component:
Open your React app (e.g., from a Create React App setup).
In the src
directory, create a new file called Greeting.js
.
// src/Greeting.js
import React from 'react';
// A functional component that returns JSX
function Greeting() {
return <h1>Hello, welcome to the React app!</h1>;
}
export default Greeting;
Explanation:
The Greeting
component is a simple function that returns an h1
element with a message.
export default Greeting;
: This allows the component to be imported and used in other parts of the app.
Using the Functional Component
// src/App.js
import React from 'react';
import Greeting from './Greeting'; // Import the Greeting component
function App() {
return (
<div>
<Greeting /> {/* Using the Greeting component */}
</div>
);
}
export default App;
Explanation:
We import the Greeting
component into App.js
using import Greeting from './Greeting';
.
In the JSX returned by App()
, we use the <Greeting />
component like an HTML tag.
Class Components (Older Syntax)
Although modern React primarily uses functional components, class components were the original way to create stateful components.
Example of a Class Component
Here’s how you would create a component using the class-based syntax:
// src/GreetingClass.js
import React, { Component } from 'react';
class GreetingClass extends Component {
render() {
return <h1>Hello from a class component!</h1>;
}
}
export default GreetingClass;
Explanation:
We extend the React.Component
class to create a class component.
The render()
method is required in class components and returns the JSX that should be displayed.
Using the Class Component
Similar to the functional component, we can import and use the class component in App.js
:
// src/App.js
import React from 'react';
import GreetingClass from './GreetingClass'; // Import the class component
function App() {
return (
<div>
<GreetingClass /> {/* Using the class component */}
</div>
);
}
export default App;