In react, html DOM elements are split into a smaller components. A component is basically responsible of generating html element. A component can take properties called props and output with a valid react element.
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. There are two types of react components:
- A functional component
- A class based component
When creating a React component, the component's name must start with an upper case letter.
What is a functional component?
A functional component can be written either with javascript function or using ES6 arrow function syntax.
Let's take a look at the example using ES6 arrow function syntax:
const GreetingsComponent = (props) => <h1>Hello, {props.name}</h1>;
Using javascript function
function GreetingsComponent(props) { return <h1>Hello, {props.name}</h1>; }
Functional components has following advantages:
- Easy to understand syntax
- Easy to write unit tests
- Less code to write
- You can use the useEffect hook v16.8
- You can use the useState hook v16.8
What is a class component?
React class components can be written with ES6 class syntax. Let's have a look at the syntax:
import React from "react" class GreetingsComponent extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
The class component has to include the extends React.Component
statement to extends some react functions to be available in the class. Defining a constructor in class component is optional however if state is used can be defined as below:
import React from "react" class GreetingsComponent extends React.Component { constructor(props) { super(props); this.state = { name: this.props.name } } render() { return <h1>Hello, {this.state.name}</h1>; } }
The component must requires a render()
method, this method returns HTML element(s).