This is Part 2 of a two-part series on how to get started with React for beginners.

In Part 1 we covered:

  • What is React?
  • Setup and Installation
  • Create React App
  • Editing React App in Code Editor

If you don’t have React installed and setup on your computer, you can follow the steps in Part 1.

In this Part 2, we’ll be covering more of the basics of React and take an more in-depth approach. We’ll be using the basic React app that was created for us through the create-react-app command.

Goals

The goal of this tutorial is to build on top of what we learned from Part 1. We’ll be covering React features such as JSX, components, state and props.

Let’s start!

JSX

In the app.js file in the src/ folder of our project, let’s remove the image and link so we only have the title remaining. Now you should have the following code (assuming you’ve followed part 1 of this tutorial).

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>My First React App</p>
      </header>
    </div>
  );
}

The code return by the function App() is an extension to the Javascript syntax called JSX. It looks alot like a template language like HTML or XML, but comes with the full capabilities of JavaScript. Let’s take a look at how to assign JSX to a variable.

const title = <h1 className="app-title">My First React App</h1>;
Note: JSX is recommended to use in React, but it isn't required. The same output can be acheived by running the `createElement` function. This method is harder to understand and write, which is why JSX is both recommended and the popular choice among React developers.

Since JSX comes with the full capabilities of JavaScript, we can acutally embed any valid JavaScript expression within curly braces {} inside JSX. This includes variables, functions and properties of objects.

const appName = "Hello World App";
const appNumber = "Second";

const title = (
  <h1 className="app-title">
    My {appNumber} React App, {appName}
  </h1>
);

console.log(title); // My Second React app, Hello World App

You might have noticed that we’ve used className rather than class for adding CSS classes. The reason is that class is a reserved keyword in JavaScript.

There’s more features and special cases to learn with JSX, but you’ll be learning about these as you start developing your own React apps.

Components

In Part 1 we mentiond components and to recap, components lets us split our UI into customizable and independent UI elements.

React apps usually exists of many small components, and all of these load into the main App component. Sometimes you’ll also have components which are built by several smaller components. Basically, almost everything in React is built by components.

So far, we only have one component in our App.js. There are two types of components: Functional components and Class components.

function App() {
  return <div className="App">...</div>;
}

Our Appcomponent is a so called Functional component. Let’s look at these different types of components at how they differ.

Functional Components

The first type of component is a functional component, which is a function. Let’s create our own component. We’ll be adding a greeting button that prints out “Hello World!” in the console, nothing fancy but it will help us learn the basics.

Most components receive their own file, so let’s beging by creating one for our button component. It’s also a good idea to create a folder for our components to keep our project structured. It might seem like useless work now, but when your project grows (and the components) it’s a good convention to follow.

  1. Create a folder in src/ and name it components.
  2. Inside the newly created components/ folder, create a file called helloWorldBtn.js

In our helloWorldBtn.jsfile lets add a button which prints to console when pressed. We’ll be using an arrow function which is an feature introduced in the ES6 version of JavaScript. You should always to start the components name with a capital letter. React handles components starting with a lowercase letter as DOM tags.

import React from "react";

const HelloWorldBtn = () => {
  return (
    <button onClick={() => console.log("Hello World")}>Hello World</button>
  );
};

export default HelloWorldBtn;

Before we actually add this component to our app in the App.js file, let’s go through what we just added.

We begin by importing React, but why? There’s no reference in our code to it, so why do we need to import it? The reason is spelled JSX. Babel will transpile our JSX code so that above code instead uses the React.createElement() function.

After importing React, we create an arrow function that returns a simple button which prints “Hello World” to the console when clicked. Notice the camelCase spelling on the onClick function? This is a convetion used for methods and properties in JSX.

The last thing we do is to export our component so we can use it other files (we’ll be importing it to App.js). When exporting as default, we can omit the curly braces and import the component as default.

import HelloWorldBtn from "./components/helloWorldBtn";

Sometimes you will have multiple exports in one file and there can only be one default. In the case of not exporting it as default, we’d have to do the following.

import { HelloWorldBtn } from "./components/helloWorldBtn";

Let’s go ahead and add our HelloWorldBtn component to our app in App.js. First we import it as above, and themn we use it in our code.

import React from "react";
import "./App.css";
import HelloWorldBtn from "./components/helloWorldBtn";
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>My First React App</p>
        <HelloWorldBtn />      </header>
    </div>
  );
}

export default App;

Start your local development server.

npm start

Then go to your browser to see the HelloWorldBtn component. To see if our button prints “Hello World” when it’s clicked, we can use the console panel in the Chrome DevTools. To open the console panel, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS).

HelloWorldBtn component

Note: You might be shown a message that says "Download the React DevTools for a better development experience". The React DevTools are debugging tools for React and is highly recommended to use. It's a big help when developing React apps.

Class Components

Now let’s move on to the second type of component, class components. We’ll be changing our App component to a class component.

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <p>My First React App</p>
          <HelloWorldBtn />
        </header>
      </div>
    );
  }
}

So what’s different? Instead of creating a plain JavaScript function, we create a ES6 class and extend from React.Component. We also need to call the render() function and return a React element. Important to know is that the return can only return one parent element.

class SomeComponent extends React.Component {
  render() {
    return <div>Works</div>
  }
}

class AnotherComponent extends React.Component {
  render() {
    return (
        <div>Won't</div>
        <div>Work</div>
    )
  }
}

The syntax is one difference, but there are other differences as well. But in order to know these, we need to introduce two new React concepts: Props and State.

Props

What if we wanted to print our app name “My First React App” in our HelloWorldBtn component, how would we do this? This requires the title to be accessable in the HelloWorldBtn.js file, and this is where props (short for properaties) come in.

With props, we’re able to pass data from a parent to a child. Since our HelloWorldBtn is imported and rendered in our App component, the App is the parent and our HelloWorldBtn component is the child.

We will be passing through our title to the HelloWorldBtn component within the App.js file. Let’s see how this looks in action.

class App extends React.Component {
  render() {
    const title = "My First React App";
    return (
      <div className="App">
        <header className="App-header">
          <p>{title}</p>
          <HelloWorldBtn appTitle={title} />
        </header>
      </div>
    );
  }
}

In order to prevent redundancy, we created a variable called title which holds the title of our application.

To pass down the data to our HelloWorldBtn component, we assign the title (using curly braces since it’s a JavaScript expression) to a property called appTitle. This can be called whatever you want as long as it’s not a reserved keyword.

Our title is now passed through from App to HelloWorldBtn but it’s not in the acutal DOM yet. The data (in this case our app title) is stored in the virtual DOM, which is a “virtual” copy of the actual DOM that we can make changes to and then sync with the “real” DOM.

We can know access our app title from the HelloWorldBtn.js file. Lets add it to the “real” DOM so we can see the changes.

const HelloWorldBtn = props => {
  const { appTitle } = props;
  const greeting = `Hello world! Greetings from ${appTitle}`;
  return <button onClick={() => console.log(greeting)}>Hello World</button>;
};

The first thing to notice is that our functional component now takes a parameter props. The props will be holding all the props passed down from a parent. When we passed the data down to the HelloWorldBtn component, we called the property appTitle. So to access the app title, we call props.appTitle but use the ES6 property shortand const { appTitle } = props.

Then we create a new variable greeting and create our greeting which includes our app title. Here we use an ES6 feature called template literals, which allows us to embed a JavaScript expression within a string.

We also change so that the button prints the greeting to the console when clicked. You should now see our new greeting in the console panel in Chrome.

Passing Data With Props

With props, you have an effective way to pass data down from a parent to a child component. However, the props are read-only and the child has therefore no control over the data.

State

With state, we’ll have further control and options for handling the data flow in our React application. State is similar to props, but it’s private and fully controlled by the component itself. With state we can sace and modify data without having to save it to a database.

Let’s say that we want to keep count of how many times we’ve clicked on our button, i.e. how many greetings have been made. We want to show the count so we don’t make too many greetings.

This would be a great opportunity to use state. We begin by converting our HelloWorldBtn to a class component.

class HelloWorldBtn extends React.Component {
  render() {
    const { appTitle } = this.props;
    const greeting = `Hello world! Greetings from ${appTitle}`;
    return <button onClick={() => console.log(greeting)}>Hello World</button>;
  }
}

Notice how we changed from props to this.props? This is how you access props within a class component.

Now that the HelloWorldBtn is a class component, we can add local state to it for storing the number of clicks. We add a class constructor where we set the initial value of the state.

class HelloWorldBtn extends React.Component {
  constructor(props) {    super(props);    this.state = { greetings: 0 };  }
  render() {
    const { appTitle } = this.props;
    const greeting = `Hello world! Greetings  ${appTitle}`;
    return <button onClick={() => console.log(greeting)}>Hello World</button>;
  }
}

There are two things to take note of here:

  1. We pass props to the constructor and call super(props), where super refers to the parent class. In this case, the parent class is React.Component. For now, it’s okay if you don’t understand what we’re doing, just remember to follow this convention.
  2. We setup the state with the greetings for keeping track of the number of times the button has been clicked. We set the inital value to 0.

Now that we have setup the local state for our component, we need a way of updating the value when the button is pressed. We create a function newGreeting() which adds 1 to greetings in state.

newGreeting = greeting => {
  const { greetings } = this.state;
  const newGreetings = greetings + 1;
  this.setState({
    greetings: newGreetings,
  });
  console.log(greeting);
};

Let’s go through the function line-by-line:

  1. const { greetings } = this.state; - retreive the current value of greetings from the state.
  2. const newGreetings = greetings + 1; - create a new variable `newGreetings
  3. Update the state using the built-in method this.setState() for manipulating state. We assign greetings the new value of newGreetings.

    Note: You must use the this.setState() function when updating the state. Assigning a new value directly to this.state.greetings won't work.
  4. The greeting, which is passed to the function as a parameter is printed to the console.

Now we need to add the current value of greetings to our button and call newGreeting() when the button is clicked.

<button onClick={() => this.newGreeting()}>
  Hello World, pressed {this.state.greetings} times
</button>

The final code should look as follows.

import React from "react";

class HelloWorldBtn extends React.Component {
  constructor(props) {
    super(props);
    this.state = { greetings: 0 };
  }

  newGreeting = greeting => {
    const { greetings } = this.state;
    const newGreetings = greetings + 1;
    this.setState({
      greetings: newGreetings,
    });
    console.log(greeting);
  };

  render() {
    const { appTitle } = this.props;
    const greeting = `Hello world! Greetings ${appTitle}`;
    return (
      <button onClick={() => this.newGreeting(greeting)}>
        Hello World, pressed {this.state.greetings} times
      </button>
    );
  }
}

export default HelloWorldBtn;

Let’s go to the browswer to see the updates.

The Final App

Wrapping up

The app that we have created in this two part series, isn’t fnacy nor is it any complex. But if you’re new to React it has hopefully helped you to get some basic knowledge of the core concepts.

There is so much more to learn and do with React so don’t stop here. Start expirementing to build up your React knowledge. Be sure to check out our other React tutorials for learning and inspiration.

Please leave a comment if you have any questions or other thoughts to share. You may also contact me we any questions, or if there’s anything else you’d like to see on this blog.