Types of Components in React
In React, we mainly have two types of components:
- Functional Components
- Class based Components
Functional Component in React
Functional components are just like JavaScript functions that accept properties and return a React element.
We can create a functional component in React by writing a JavaScript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. The below example shows a valid functional component in React:
Syntax:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Example: Create a function component called welcome.
function welcome() {
return <h1>Hello, Welcome to w3wiki!</h1>;
}
Class Component in React
The class components are a little more complex than the functional components. A class component can show inheritance and access data of other components.
Class Component must include the line “extends React.Component” to pass data from one class component to another class component. We can use JavaScript ES6 classes to create class-based components in React.
Syntax:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}
The below example shows a valid class-based component in React:
Example: Create a class component called welcome.
class Welcome extends Component {
render() {
return <h1>Hello, Welcome to w3wiki!</h1>;
}
}
The components we created in the above two examples are equivalent, and we also have stated the basic difference between a functional component and a class component. We will learn about more properties of class-based components in further tutorials.
React Components
Components in React serve as independent and reusable code blocks for UI elements. They represent different parts of a web page and contain both structure and behavior. They are similar to JavaScript functions and make creating and managing complex user interfaces easier by breaking them down into smaller, reusable pieces.