
React Components
Components are reusable pieces of codes. React Components are similar to Javascript functions, just differ slightly as they return HTML using the render()
method.
In ReactJS, we mainly have two components:
- Class Components
- Functional Components
Class Components
In Class Components, the component name starts with a capital letter, and extends React.Component
. With this, our Class gets inherited from React.Component
, and can access all its functions.
Another important component is the render()
method. Here's a simple example:
import React from 'react'
class FirstComponent extends React.Component {
render(){
return (
<h3>Our Class Component </h3>
)
}
}
Class Component is also known as stateful component as it can hold & manage states.
For displaying the FirstComponent
in the root element, we can simply do like this:
ReactDOM.render(<FirstComponent />, document.getElementById('root'));
Constructor in Class Components
A constructor()
function is used to initialize an object's state, and is called when the component is initialized. The concept of a constructor()
function is same in React.
State is always initialized inside the constructor. All the component properties shall be kept inside the state. We'll be covering states in the next tutorial. Here's an example with the constructor:
class FirstComponent extends React.Component {
constructor(){
super()
this.state = {
name: 'John Doe'
}
}
render(){
return (
<h3>Our Class Component with Name : {this.state.name}</h3>
)
}
}
By including the super()
method, we inherit all the function of the base class. super()
is used to execute the parent component's constructor function.
Functional Components
Functional components is another way of writing components in React. They are also called stateless components as they don't have a state. Functional components also return HTML, the same way as Class Components. Let's have a look at a functional component:
function FirstComp(){
return (
<div>
<h1>This is a functional Component</h1>
</div>
)
}
The functional components are rendered the same way as Class Components:
ReactDOM.render(<FirstComp />, document.getElementById('root'));
Including Components within Components
The best thing about react is that we can re-use the components whenever and wherever needed. Components can be kept into seperate files, and can be used when needed.
Let's create a new component; a component must have an export statement:
//NewComp.js
function NewComp(){
return (
<div>
<h2>This is another functional Component</h2>
</div>
)
}
export default NewComp
To be able to use the NewComp
, you need to import it:
import React from 'react'
import NewComp from './NewComp'
function App(){
return (
<div>
<h1>Main Component</h1>
<NewComp/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
This is how it will look like:
