Meet the First React Component
Explore the fundamentals of React by creating your first function component called App. Understand how JSX works within the component, the role of function components, and how variables are managed in React. Gain a clear foundation in component structure to prepare for building more complex React applications.
We'll cover the following...
Our first React component is in the src/App.js file, which should look similar to the example below. The file might differ slightly because create-react-app will sometimes update the default component’s structure.
This file will be our focus throughout this tutorial unless otherwise specified. Let’s start by reducing the component to a more lightweight version for getting you started without too much boilerplate code from create-react-app.
To understand components in React, we can break down the App component into three main parts:
- First, this React component, called App component, is similar to a JavaScript function but not particular javascript function. It’s commonly called function component, because there are other variations of React components (see component types later).
- Second, the App component doesn’t receive any parameters in its function signature yet (see props later).
- Third, the App component returns code that resembles HTML which is called JSX.
The function component possesses implementation details like any other JavaScript function:
Variables defined in the function’s body will be re-defined each time this function runs, like all JavaScript functions:
Since we don’t need anything from within the App component used for this variable – e.g. parameters coming from the function signature – we can define the variable outside of the App component as well:
The complete code:
import React from 'react';
const title = 'React';
function App() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
export default App;
Let’s use this variable in the next lesson.
Exercises:
Test your knowledge!
Which of the following is true about React components? (Select Multiple Answers) Multi-select
Components are independent
Components are reusable bits of code
Components returns JSX via a render function
Identical to Javascript functions