Today, we’ll look at two features covered in our new React course, Powering Up With React, and see different ways we can write those features.
Creating React Components
The very first thing we learn in React is how to create a component — the most common way to do that is using the class syntax, like this:
As you can see in the previous example, Greeting is a function that takes one argument — the props object. We can use the props object to read arguments passed to the Greeting component, and this component can be used just like any other React component, like on the following example:
Exporting React Components
The simplest way to run a React application is by transpiling ES2015 and JSX code on the fly — this saves you time because it lets you avoid setting up a build system. While this is the strategy we used in Powering Up With React, you would most likely use a build system in a real-world scenario.
Another benefit of build systems is the ability to use ES2015 features that browsers have not yet implemented — one such feature is the module system. Separating each component into its own module makes it easier to understand the codebase and avoids conflicts when our team grows and multiple people have to edit files at the same time.
Here’s an example of a React component inside its own module:
The class part should be familiar, and on the last line, we export this class so other modules can import this module and invoke the component, like so:
When working with stateless function components, the syntax for exporting a module is the same:
And we can import it and use it from another module just like before:
These are just two React and ES2015 features for you to look into further as you learn the basics of React — which you can get a headstart on now by playing Powering Up With React.