Monday, 8 July 2019

React Component

What is component is React JS?
In react component represents a part of the user interface.A application may have five components header,Side nav,Main content,footer and one root component which
contains other components i.e. Root component is  AppComponent which holds all other components.

Component code can be placed as java script file for example App Component is placed as App.js under your sample react application.
Component basically a code inside the .js file.

Types of component
1)Stateless Functional Component
Functional component is literally a java script functions Which return a html.
Functional component optionally receives of Properties which is refereed to as props and returns as HTML which describe UI.
ie
function Welcome(props){
  return <h1>Hello ,{props.name}</h1>
}

First Functional Component

  • Create one component as Greet.js in src/components folder.

import React from 'react'

function Greet() {
return <h1>Hello Pradeep</h1>
}
export default Greet

  • Import into App.js and Specify Greet Custom tag as below

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from './components/Greet'

function App() {
return (
<div className="App">
<header className="App-header">
<Greet/>
</header>
</div>
);
}

export default App;

2) Stateful Class Component
Class component is a fast component which extends Components class from react library.
Which must render method and  returning HTML.
i.e.
class Welcome extends React.Component{
  render(){
     return <h1>Hello, {this.props.name}</h1>
  }
}
Class components are basically ES6 classes.Similar to a functional component, class component  also can optionally receive props and return html.

Creating a simple class component:
1)Create a file Welcome.js file in component folder as below.
import React,{Component} from 'react'
class Welcome extends Component{
render(){
return <h1>First component class</h1>
}
}
export default Welcome
2)Whenever we are going to create a class component, need to include two imports
one is React and second one is {Component} class from react library.
3)To make a class a react class, there are two simple steps

  • Class should extend Component class from react lib.
  • Class has to implement render method and should return null or some HTML
4)Import class component in App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from './components/Greet'
import Welcome from './components/Welcome'

function App() {
return (
<div className="App">
<header className="App-header">
<Greet/>
<Welcome/>
</header>
</div>
);
}
export default App;

Start the server and feel the impact.



No comments:

Post a Comment