As per the official documentation
Run npx create-react-app app-name
This is a basic JS function. Where we can pass props as shown below (This is a sample Functional Component). Before React 16.8 we cannot setState and Lifecycle Hooks using functional components.
import React from 'react';
function BasicFunctionalComponent(props) {
return <p>Rashain {props.last}</p>;
}
export default BasicFunctionalComponent;
To pass Prop to the above code
import FunctionalComponent from './components/functional-component';
<FunctionalComponent last={"Jayanetty"} />
This is ES6 Class that extends React.Component and has to be wrapped inside render() method.
Here’s an example of ES6 Class
class BasicClass {
return <p>Hey</p>
}
Here’s an example of React Classes
import React, {Component} from 'react';
class BasicClassComponent extends Component {
render() {
return <p>Hey</p>
}
}
export default BasicClassComponent;
We can define State generally within a Class. We are not able to use State in Functions before 16.8. We can set state as;
class BasicClassComponent extends Component {
state = {
dateLabel: "It is ",
date: new Date()
}
render() {
return (
<h2>
{this.state.dateLabel}
{this.state.date.toLocaleTimeString()}
</h2>
)
}
}
But doing so we will not have access to Props. Therefore we need to define the state inside the constructor() method as shown below;
class BasicClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
dateLabel: "It is ",
date: new Date()
}
}
render() {
return (
<h2>
{this.state.dateLabel}
{this.state.date.toLocaleTimeString()}
</h2>
)
}
}
Doing so it is mandatory to add super() method.
There are 3 types;
This is the method called when a created component needs is added to the DOM. This contains;
This is when the component is changed. This contains;
This contains;
Just like in JS we add onClick event. As shown below;
class TodoAdd extends React.Component {
handleClick() {
console.log("Hey I'm Clicked");
}
render() {
return (
<React.Fragment>
<button onClick={this.handleClick}>
Click Me
</button>
</React.Fragment>
)
}
}
As per the documents its a must to bind this.
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
If not the it will return undefined when states are involved.