React Components

A component is a piece of code that is independent and reusable. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.
It is basically isolated, reusable and independent pieces of code.
There are two types of components.
- Class components
- and Function components
Class Component
- Class components required you to extends React.Components and creates a render() method which returns react element.
- this is also known as state full component because its implements logic and states.
- takes Props (in the constructor) if needed
- React lifecycle methods can be used inside class components.
State React object => where you store property values that belong to the component.
render() method => to display the specified HTML code inside the specified HTML element.
Create Your First Component
class Welcome extends React. Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
When creating a React component, the component’s name MUST start with an upper case letter.
Function Component
The first and recommended component type in React is functional components. A functional component is basically a JavaScript/ES6 function that returns a React element (JSX).
So a Functional Component in React:
- is a JavaScript/ES6 function
- must return a React element (JSX)
- takes props as a parameter if necessary
function Welcome (props) {
render() {
return <h1>Hello, {props.name}</h1>;
}
}
When creating a React component, the component’s name MUST start with an upper case letter.
When to use a Class Component over a Function Component in ReactJS?
Functional Components
- A functional component is just a plain JavaScript pure function that accepts props as an argument and returns a React element(JSX).
- There is no render method used in functional components.
- Hooks can be easily used in functional components to make them Stateful.
example: const [name,SetName]= React.useState(‘ ‘)
- Constructors are not used.
it is also known as Stateless components as they simply accept data and display them in some form, they are mainly responsible for rendering UI.
Class Components
- A class component requires you to extend from React. Component and create a render function that returns a React element.
- It must have the render() method returning JSX (which is syntactically similar to HTML)
- It requires different syntax inside a class component to implement hooks.
example: constructor(props) {
super(props);
this.state = {name: ‘ ‘}
}
- Constructor is used as it needs to store state.
it is also known as Stateful components because they implement logic and state.
