Components are independent, reusable code units that function like JavaScript functions but return HTML. They come in two types: Class components and Function components; this tutorial will focus on Function components.
In older React codebases, Class components were commonly used. However, it is now recommended to use Function components with Hooks, introduced in React 16.8. An optional section on Class components is available for reference. |
When defining a React component, its name must start with an uppercase letter.
A class component must include extends React.Component to inherit from React.Component, granting access to its functions. Additionally, the component must define a render() method, which returns HTML.
Here’s an example of a Class component called Car
:
class |
Here’s the same example using a Function component:
A Function component also returns HTML and functions similarly to a Class component, but requires less code, is easier to understand, and will be preferred in this tutorial.
Here’s an example of a Function component called Car
:
function |
Now your React application includes a Car
component that returns an <h2>
element. To use this component in your application, you can incorporate it with the syntax <Car />
, similar to regular HTML.
Render the Car
component inside the “root” element.
const |