What is component?
Components are basic building blocks of Ract App. A component is a class or a function that accepts inputs and returns react element that describes how the user interface should look. Components are independent and re-usable.
There are main two types of Components
- Class Component
- Functional Component
Class Component
A Class component requires you to extends from React.Components and create a Render function that returns a React Element. A class component is called as statefull class component. Whenever the state of the components changes the render method will call.
For Example
Create Class Component name as Demo
class Demo extends React.Component
{
render()
{
return <h1>Hello, I am Rohitraj!</h1>;
}
}
Functional Component
A Functional component accepts props as an argument and returns a React Element. There is no render method used in funtional component. A function component is called as stateless functional component. It render the user interface based on props.
For Example
Create Funtional Component name as Demo
function Demo()
{
return <h1>Hello, I am Rohitraj!</h1>;
}
Rendering a Component
Rendering a component means a component with render prop which takes a funtion that returns a React Element and call it.
Given below is the example where ReactDOM.render renders your component i.e. to the DOM in the root element.
Example
ReactDOM.render(<Demo />, document.getElementById('root'));
Components in Component
we can use components inside other component. Means we can create multiple funtions in one component and return one function into another funtion.
Example
function Demo() {
return <h1>I am Rohitraj!</h1>;
}
function Sample() {
return (
<>
<h1>Who are you?</h1>
<Demo />
</>
);
}
ReactDOM.render(<Sample />, document.getElementById('root'));
Components in Files
We can create a new file with .js extension and inside that we create a funtion and returns some HTML element and we export this function. Given below you can see the example:-
Example
This is the new file we called it as Demo.js
function Demo() {
return <h1>Hello, I am Rohitraj!</h1>;
}
export default Car;
This is what we called a Demo Component. Now you have to import this file in your application. So for that we use the import statment then the function_name and the path where the file is located. Given below you can see this:-
import React from 'react';
import ReactDOM from 'react-dom';
import Demo from './Demo.js';
ReactDOM.render(<Demo />, document.getElementById('root'));
Top comments (0)