Curriculum
Course: React
Login

Curriculum

React

Text lesson

React Components

React Components

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.

Create Your First Component

When defining a React component, its name must start with an uppercase letter.

Class Component

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.

Example

Here’s an example of a Class component called Car:

class Car extends React.Component {
 render() {
    return <h2>Hi, I am a Car!</h2>;
 }
}

Function Component

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.

Example

Here’s an example of a Function component called Car:

function Car() {
 return <h2>Hi, I am a Car!</h2>;
}

Rendering a Component

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.

Example

Render the Car component inside the “root” element.

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);