Creating our first component

We can create a basic Header component and reference it within our App component by carrying out the following steps:

  1. Create a new file called Header.tsx in the src folder.
  2. Import React into the file with the following import statement:
import React from 'react';
  1. Our component is just going to render the word header initially. So, enter the following as our initial Header component:
export const Header = () => <div>header</div>;

Congratulations! We have implemented our first function-based React component!

The preceding component is actually an arrow function that is set to the Header variable.

An arrow function is an alternative function syntax that was introduced in ES6. The arrow function syntax is a little shorter than the original syntax and it also preserves the lexical scope of this. The function parameters are defined in parentheses and the code that the function executes follows a =>, which is often referred to as a fat arrow

Notice that there are no curly braces or a return keyword. Instead, we just define the JSX that the function should return directly after the fat arrow. This is called an implicit return. We use the const keyword to declare and initialize the Header variable.

The const keyword can be used to declare and initialize a variable where its reference won't change later in the program. Alternatively, the let keyword can be used to declare a variable whose reference can change later in the program.
  1. The export keyword allows the component to be used in other files. So, let's use this in our App component by importing it into App.tsx
import { Header } from './Header';
  1. Now, we can reference the Header component in the App component's render method. Let's replace the header tag that CRA created for us with our Header component. Let's remove the redundant logo import as well:
import React from 'react';
import './App.css';
import { Header } from './Header';

const App: React:FC = () => {
return (
<div className="App">
<Header />
</div>
);
};

export default App;
  1. In the Visual Studio Code Terminal, enter npm start to run the app. We'll see that the word header appears at the top of the page, centered like so:

Congratulations again – we have just consumed our first React component!

So, the arrow function syntax is a really nice way of implementing function-based components. The implicit return feature that arrow functions have reduces the number of characters we need to type. We'll use arrow functions with implicit returns heavily throughout this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.222.231