Create React App 2 Quick Start Guide
上QQ阅读APP看书,第一时间看更新

Creating our first component

To create our first component, follow these steps:

  1. Open up the newly-created project in your favorite text editor, and run the start command in that project as well to bring up the browser window to see the results of any changes we make along the way.
  2. Let's do something all developers love to do: delete old code!
  3. Once in the code, we can work through the main primary ways to work with React in the latest JavaScript syntax changes that are included in Babel. Given that, let's take a look at the ways to work with React classes. We can either use functions, or we can use classes to introduce React code to our code base. We'll start off with just using functions and over time incorporate classes as well, and we'll discuss how, when, and why to choose each along the way. Granted, either creation method requires React regardless of the implementation method, so we need to actually import it at the start of our code.

  1. At the very top of the App.js file, we're going to add our import statement:
import React from 'react';

This line tells JavaScript that we want to import the React library, and that we can find the React class from the react npm library (Create React App obviously already included that for us). This gives our code the React support that we need, plus it adds support for JSX templates, and everything else we need to be able to write base-level JavaScript !

  1. With our imports out of the way, let's write up our first bit of code:
const App = () => {
return <div className="App">Homepage!</div>;
};

Here, we're diving a little further into some new JavaScript syntax that you may not be used to if you're coming from the older JavaScript world. The previous line is responsible for creating something called a constant function, which limits our ability to redefine or modify the App function after the fact. This function that we're writing doesn't take any arguments and always returns the same thing. This is a functional component, so we need to write the return statement to return out a JSX template that tells React how to render our React component to the browser. We also make sure to tell React that our main component should have a CSS class name called App.

The className, not class! Class is a reserved keyword in JavaScript , so that's why React needs this one little gotcha!
  1. At the end of this code, we'll need to add an export statement to enable other files (such as our index.js file, specifically) to be able to import the right modules into our code base:
export default App;

Our end result is that when our browser refreshes, we should see Homepage! pop up on the screen!