Suggested Reading:Pages 15-43 of the React book

Getting started with React

These notes will guide you through the process of setting up your first example React application.

React requires that you have the node.js development tools installed. If you have not done so already, go to the download page for node.js to download the installer for node.js.

Next, create a project folder on your computer for your React projects. Start up Visual Studio Code and open that project folder in Code.

To set up our first React project we will have to run some commands in the terminal. The most convenient way to do this is to use the built-in terminal pane in Code. To open the terminal pane, select New Terminal from the Terminal menu in Code.

The author of our React text uses the Vite build system to set up and build all of his example projects, so we will be doing the same. To create our first example project with Vite using the node package manager (npm), run this command in the terminal pane:

npm create vite@latest hello-react -- --template react

This will create a project folder named hello-react. The project starts out with some default content provided by Vite. You can run the project to see its initial state by running the following commands in the terminal:

cd hello-react
npm install
npm run dev

After the last command you will see a URL in the terminal that points to our application running in the development server. Hold down the control key and click on that URL to open the page in a browser.

In that first page you will see some content provided by Vite. One of the components displayed is a counter component that you can click on to increment the component's counter value.

Parts of a React project

You can examine the structure of the project folder we just created in the file explorer view in Code. At the top level of the project folder you will see an index.html file. This file contains the minimal HTML code needed to set up a React project. In that HTML code you will see a root div that React will be inserting its content into and a script element that loads the main.jsx file.

The other part of the project that we will be working with is in the src folder in the project folder. The first file that the HTML page loads is the main.jsx file, which contains just enough React code to load the main component in our example React app, the App component.

The code for the App component is located in the App.jsx file. If you open that file you will see that it contains the code for a single function, the App() function. We will be modifying the code for this function a couple of times in these notes to demonstrate the basics of setting up a React component.

Say Hello to React

For our first example we are going to replace the code for the App() component function with a much simpler example:

function App() {
  return (<h1>Hello from React!</h1>);
}

Since we are running our React app in the development server, we get to take advantage of Vite's live reload feature. As soon as you save your changes to the App.jsx file the system will recompile your project and load the new version of the project in the browser.

This first snippet of example code demonstrates a powerful feature of React code. When we write code for a React application we will be using JSX, which is a specialized programming language that allows us to mix JavaScript and HTML freely in a single file. When you save your changes to the App.jsx file, the Vite build system will run a tool called a transpiler that will automatically translate your JSX code into pure JavaScript.

This first example demonstrates on of the primary goals of React component functions. Each component function is expected to return a snippet of HTML code to be inserted into the page.

An interactive example

For our second example today I am going to construct a more complex component that includes interactive elements such as a text field and a button.

Replace the code for the App() component function with this:

function App() {
  const [name,setName] = useState('');
  const nameInput = useRef();

  function doGreeting() {
    setName(nameInput.current.value);
  }

  if(name.length == 0)
    return (
      <div>
        <label htmlFor="name">Enter your name</label>
        <input type="text" ref={nameInput} id="name" />
        <button onClick={doGreeting}>Greet Me</button>
      </div>
    );
  else
    return (
      <p>Hello, {name}! Welcome to React.</p>
    );
}

You will also need to update one of the import statements at the top of the file. Replace

import { useState } from 'react'

with

import { useState, useRef } from 'react'

The first important new feature in this example is the use of a React state variable. State variables play an important role in the life of React components. Whenever the value of a state variable changes, React will invoke the component function to rebuild the component to reflect the component's new state. In this example I set up a name state variable. The statement

const [name,setName] = useState('');

sets up this state variable and gives it an initial value, which is an empty string. To read the current value of the state variable, we use the name variable declared here. To change the value of this state variable we will use the setName() function, which is also set up here.

Further down in the code for the App() function you will see an if statement that renders the component in one of two forms. At start, when the state variable is empty, the if statement will return an HTML div element containing a label, a text input field, and a button. When the user clicks the button the code will read the contents of the text input field and put them in the name variable. When the component re-renders after that, we will instead take the branch of the if statement that returns a paragraph element containing a greeting.

In the greeting you will see an important aspect of JSX code. JSX allows us to insert JavaScript expressions in our HTML by putting little snippets of JavaScript inside {} groups. In this case, we are inserting the current value of the name state variable into the greeting we show the user.

This example also demonstrates the basics of event handling in React. In this example code I attached an event handler to the button:

<button onClick={doGreeting}>Greet Me</button>

In this case, I am setting up a JavaScript function as an event handler for the click event on the button. You can see the definition of the doGreeting() function near the top of the App() function:

function doGreeting() {
  setName(nameInput.current.value);
}

One other small technical issue I needed to solve here was getting the value of the text input element. React provides a solution to this problem through the use of references. To do this, I start by introducting a special React variable called a reference variable:

const nameInput = useRef();

Then, when I set up the text input field I give it a special ref attribute:

<input type="text" ref={nameInput} id="name" />

Finally, when I need to read the value of the text input field I can do that through the reference variable:

nameInput.current.value