React Component
A React component describes a part of the UI. Its purpose is to return HTML to a web page.
There are two ways to create React components.
Function Component
function App(props){
return <h1>Hello World</h1>
}
export default App;
- The name must have an uppercase first letter.
- The function component must be the default export.
- The function must return a React element (can use JSX).
- The argument
props
can be omitted if "props" are not used. - Function components used to be called "state-less components." However, with the introduction of "Hooks" (since React 18), function components can hold "state."
You can define function components using the arrow function.
const App = () => {
return <h1>Hello World</h1>
}
export default App;
Class Component
We won't use class components! So, you may skip this section.
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
greeting: "Hello World"
}
}
render() {
return (
<h1>{this.state.greeting}</h1>
);
}
}
export default App;
- A class component must extend the
Component
class fromreact
library. - A class component must have a
render
method that a React element (can use JSX). - A class component should have a constructor that receives a
props
argument and passes it to the parent constructor (using thesuper
keyword). If the constructor has no other purpose, it can be omitted. - The class component must be the default export.
- Class components are also called state-full components.
- The component's "state" must be stored in an object called
state
. This object must be a class property. It can be declared inside the constructor or as a field.
import React, { Component } from "react";
class App extends Component {
state = {
greeting: "Hello World"
}
render() {
return (
<h1>{this.state.greeting}</h1>
);
}
}
export default App;