In part one of this tutorial series, we used the create-react-app
tool to create a working sample app as a starting point for our ‘Movie Mojo’ gallery app.
In part two, we’ll get to grips with adding our first custom component to display individual movie cards. We’ll also see how using props allows us to customize the appearance of components by passing in data rather than hard coding it.
This demonstrates the flexibility and reusability of components, and how they can be used as powerful building blocks in your React apps.
Our First Component
OK, let’s create a component! To start with, we’ll keep things fairly simple and refactor the header HTML into its own component.
Modern React best practices recommend separating out each component in your app into a separate file. We’ll be following this principle so, in your projects /src/components/
folder, create a new file called Header.js
and open it in a text editor.
At the top of component files we always start by importing required libraries, other components (as we can nest components), and extra assets we need (e.g. styles). The import
statement is part of ES6 and allows us to keep our projects highly modular.
For our
component, we only need to import the React library, which we can do with this statement:
import React, { Component } from 'react';
This imports the entire React library and makes it available via the React
variable. It also imports the Component
object directly so we can use it without having to specifically qualify it with a preceding React.
object reference.
In other words, if we didn’t explicitly import the Component
object then we’d have to access it as follows:
React.Component
But because we imported Component
directly, we can just use it on its own without any reference to the React
variable. It doesn’t matter which one you use, and is just down to preference.
Next, to actually create the component, we extend the Component
object to create a new class that defines our
component. After the import
statement, type:
class Header extends Component { } export default App;
Here, we use an ES6 class as our component container. Classes are a great way to encapsulate all the code needed to describe your component.
You might have also noticed that the component file ends with an export statement. This, as you might expect, exports our component and makes it available to other files in our project.
At the very minimum, all React components are required to have a render method, which returns some markup. This could be HTML, other React components, or a mixture of both.
Add this inside your component class:
render() { return React.createElement( 'div', null, 'Hello there, this is a React component!' ); }
The React.createElement()
method creates an HTML element (a
Header.js
and open up App.js
.
To use a React component inside another component, we first need to import it, so add this to the list of import statements at the top of App.js
:
import Header from './Header';
Note how you don’t need to add the .js
file extension as this is assumed. Also, because the
component is in the same folder as our
component, we don’t need to specify the full path.
In fact, if you try to use import Header from './components/Header';
from inside App.js
, you’ll get a compilation error.
We can now add the
component inside the return statement just like any HTML element. However, there is a caveat. You can only return one top-level element inside a components return method.
So this is not allowed:
render() { return ( ); }
If you want to return multiple elements then you have to wrap them all up inside a single wrapper element:
render() { return (); }
So make sure that you add the
component inside the
class App extends Component { render() { return (); } }Discover Your Movie Mojo!
Welcome to the 'Movie Mojo' React app!
This will result in our
component being rendered.
To complete the
component, we’ll remove the following block of HTML from App.js
and add it to Header.js
.
Discover Your Movie Mojo!
However, you might have noticed there is an issue. In App.js
the
component render method returns what looks like HTML. Yet in Header.js
there’s just a single call to React.createElement()
. What’s going on?
The answer is JSX. In App.js
we use JSX to write HTML-like syntax to define our component output. Compare this with our component definition for Header.js
.
React.createElement( 'div', null, 'Hello there, this is a React component!' );
This is how we have to write React components without JSX. In fact, under the hood, this is what JSX is compiled into before it can be rendered to the browser.
You’re not required to use JSX at all for your React components; it is entirely up to you. But almost all components you’ll come across will be written in JSX because it’s just so much easier to write.
It’s also highly readable for others new to your code. Imagine having to study a React project containing dozens of different components written in plain JavaScript!
So it should come as no surprise that we’ll be using JSX for component definitions throughout the remainder of this tutorial series.
Go ahead and replace the React.createElement()
call with the JSX equivalent we copied from App.js
. Your Header.js
file should now look like this:
import React, { Component } from 'react'; class Header extends Component { render() { return (); } } export default Header;Discover Your Movie Mojo!
While JSX allows us much more flexibility in writing our components, bear in mind that it isn’t actual HTML we’re writing but an abstraction of it.
You can see this in the code snippet above. Notice in the
className
rather than class
to indicate where we want to declare a CSS class? This is because all JSX is compiled down to pure JavaScript, and class
is a reserved word in ES6 JavaScript.
Let’s also tweak the header styles. Open App.css
and edit the .App-header
CSS class to be:
.App-header { background-color: steelblue; height: 70px; padding: 20px; color: white; }
This updates the background color of the header and reduces the height.
Component Props
So far, our
component is static. That is, it displays fixed content that never changes. But components can be made to be dynamic and display content passed into them, via component props. This makes components suddenly much more useful as they become generic and reusable.
Think of component props as similar to HTML tags. For example, a
id
, class
, style
and so on that enable us to assign unique values for that specific
element.
We can do the same for React components. Say we didn’t want our header to output the fixed text ‘Discover Your Movie Mojo!’ all the time. Wouldn’t it be better if our header could display any text?
Unlike HTML attributes, we can name our component props whatever we like. Inside App.js
, update the
tag to be:
Then, update the
component to use the text
prop.
{this.props.text}
This results in our header displaying whatever text is added to the text
prop in App.js
.
Let’s take a closer look at how we referenced the text
prop inside Header.js
using:
{this.props.text}
The curly braces simply tell JSX that we have some JavaScript we want to evaluate. This distinguishes it from text. If we didn’t use any curly braces, the string literal this.props.text
would be outputted, which isn’t what we want.
The this
keyword refers to the Header
component class, and props
is an object that contains all the values passed in from
. In our case, the props
object contains just the one entry, but you can add as many as you like in practice.
Our
component is now much more generic and doesn’t contain a hard-coded string. This is a good practice when writing React components. The more generic you make them, the more reusable they are.
This is good news when developing future React apps as you can reuse components from previous projects so you don’t have to write everything from scratch.
We used props above to pass a fixed string into the
component, but props can also pass variables, function references, and state to components.
To send a variable via props, we could do something like this, where headerText
is a variable:
Inspecting React Components
There’s a very useful tool available for the Chrome browser that lets you inspect information about your React app.
The default developer tools only allow you to view normal HTML elements, but with the React Developer Tools extension installed, you can navigate through all the React components in your app.
Once it’s installed, open your browser inspector tools, and click on the newly available React tab. Notice that instead of HTML elements, you see the hierarchy of React components in your app. Click on the
component to select it.
Once selected, information about a component is displayed in the window to the right. The
component doesn’t have any props and so the window is empty. But if you select the
component inside
then you’ll see the ‘text’ prop we passed in.
The React developer tools are very useful for debugging, especially when you get onto developing more complex React apps, so it’s well worth getting used to using them on simpler apps.
You can also use the React developer tools to inspect your application state, which we’ll get into in the next tutorial.
Conclusion
In this tutorial you learned how to split your app into separate components to make it more modular. Component props enable you to pass in values to individual components, similar to how you add attributes to HTML elements.
We also saw how to leverage new browser inspector tools to examine components and props data.
In part 3, we’ll add state to our app to help us manage our data more effectively.
Powered by WPeMatico