React Components
What are React Components?
A React Component is a self-contained and re-usable part of an application. Components can be created in two different ways:
- Functional components
- Class components
Functional Components
A functional component is a JavaScript function which returns JSX and can be rendered on a page.
The most basic functional component has a name and returns a JSX element.
import React from 'react';
export function App() {
return <h1>Welcome to my App.</h1>;
}
Class Components
Components can also be created using a class which extends React.Component and inherits the functions that a component requires. React recommend defining components in functions instead of classes.
import { Component } from 'react';
export default class App extends Component {
render() {
return <h1>Welcome to my App.</h1>;
}
}
Outputting variables in Components
As this is a JavaScript function and it returns JSX, we can output variables within the HTML.
import React from 'react';
export function App() {
const today = new Date();
return (
<>
<h1>Welcome to my App.</h1>
<p>The year is {today.getFullYear()}</p>
</>
);
}
<h1>Welcome to my App.</h1>
<p>The year is 2025</p>
When outputting multiple lines in a return statement, there must only be one parent element otherwise React will throw an error. In the example above we’ve wrapped our heading 1 and paragraph inside a React Fragment which begins with <>
and ends with </>
.
A <div>
could have been used instead, but the advantage of React Fragments is that no extra HTML elements are added to the DOM.
A React component is a great way to output lists of data from arrays or objects by iterating over each item and rendering its value.
import React from 'react';
export function App() {
const cars = ['Ford', 'Audi', 'BMW',];
return (
<>
<h1>List of cars
<ul>
{
cars.map((car, index) => {
return <li key={index}>{car}</li>;
})
}
</ul>
</>
);
}
<h1>List of cars</h1>
<ul>
<li>Ford</li>
<li>Audi</li>
<li>BMW</li>
</ul>
So far we’ve only dealt with variables defined within the component. In the next article we’ll look at how we can pass data between components using props.