React js как запустить

от admin

Installation

React is flexible and can be used in a variety of projects. You can create new apps with it, but you can also gradually introduce it into an existing codebase without doing a rewrite.

Trying Out React #

If you're just interested in playing around with React, you can use CodePen. Try starting from this Hello World example code. You don't need to install anything; you can just modify the code and see if it works.

If you prefer to use your own text editor, you can also download this HTML file, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so don't use it in production.

Creating a Single Page Application #

Create React App is the best way to starting building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. It uses Webpack, Babel and ESLint under the hood, but configures them for you.

Adding React to an Existing Application #

Using npm #

We recommend using React from npm with a bundler like Browserify or webpack. If you use npm for client package management, you can install React with:

and import it from your code with something like:

This code renders into an HTML element with the id of root so you need <div > somewhere in your HTML file. When you use React in this way, you should be transpiling your JavaScript using Babel with the es2015 and react presets. To use React in production mode, set the environment variable NODE_ENV to "production" .

If you use Bower, React is available via the react package.

Enabling ES6 and JSX #

We recommend using React with Babel to let you use ES6 and JSX in your JavaScript code. ES6 is a set of modern JavaScript features that make development easier, and JSX is an extension to the JavaScript language that works nicely with React. The Babel setup instructions explain how to configure Babel in many different build environments. Make sure you install babel-preset-react and babel-preset-es2015 and enable them in your .babelrc , and you're good to go.

Using a CDN #

If you don't want to use npm to manage client packages, the react and react-dom npm packages also provide UMD distributions in dist folders, which are hosted on a CDN:

To load a specific version of react and react-dom , replace 15 with the version number.

Введение в React JS

В этой статье я постараюсь разложить основы создания приложения на React.JS на составляющие. Начнем с рассмотрения как создать приложение React JS.

Что такое React JS?

React — это библиотека JavaScript для создания пользовательских интерфейсов. React следует философии Unix, потому что это небольшая библиотека, которая фокусируется только на одном деле и делает это очень хорошо (т.е. на создании пользовательских интерфейсов).

Пользовательский интерфейс (UI) — это все, что мы помещаем перед пользователями, чтобы они могли взаимодействовать с машиной.

React декларативен, т.е. мы описываем UI с помощью React и говорим ему, что мы хотим (а не как это сделать). React позаботится о том «как сделать» и переведет наши декларативные описания (которые мы пишем на языке React) в реальные пользовательские интерфейсы в браузере. React разделяет эту простую декларативную силу с самим HTML, но с React мы получаем декларативность для пользовательских интерфейсов HTML, которые представляют динамические данные, а не только статические данные.

DOM — это «объектная модель документа». Это программный интерфейс браузеров для документов HTML (и XML), который обрабатывает их как древовидные структуры. DOM API можно использовать для изменения структуры, стиля и содержимого документа.

React изменил правила игры, потому что он создал общий язык между разработчиками и браузерами, который позволяет разработчикам декларативно описывать пользовательские интерфейсы и управлять действиями с их состоянием вместо действий с элементами DOM. Это просто язык «результатов» пользовательского интерфейса. Вместо того, чтобы придумывать шаги для описания действий в интерфейсах, разработчики просто описывают интерфейсы в терминах «конечного» состояния (например, функции). Когда в этом состоянии происходят действия, React заботится об обновлении пользовательских интерфейсов в DOM на основе этого (и делает это эффективно).

Создание приложения React JS App

Для начинающих разработчиков не нужно арендовать хостинг, либо платить за сервисы по развертыванию среды для разработки react js. Достаточно на своем компьютере или ноутбуке установать node.js. Делается это в три клика.

Установка Node.js

Далее запускаем инсталлятор, все шаги стандартные, жмем next-next-next. Вот этот пункт можете оставить по умолчанию неактивным:

После завершения установки у Вас в пункте меню появятся программки:

Также в директории C:\Program Files\nodejs\ лежат файлы

Создаем приложение React JS App

Для установки react js нам понадобится консоль. Вы можете запустить Node.js command prompt. Я предпочитаю использовать far manager. Тут кто где привык работать.

Итак, создадим директорию нашего проекта — приложения React JS, например:

Далее в консоли перейдем в эту папку и запустим команду для инсталляции create-react-app

Для этого в консоли запустим команду npm i -g create-react-app

Теперь нам необходимо создать приложение с помощью установленного на предыдущем шаге инструмента create-react-app. Инструмент create-react-app был создан Facebook и является рекомендуемым способом создания нового проекта.

Наше первое приложение будет называться hello_react. Для его создания запустим команду:

npx create-react-app hello_react

Запустится инсталляция приложения. Идет она примерно 5 минут (зависит на самом деле от скорости интернета, т.к. все зависимости скачиваются из интернета). Итак, в конце установки у вас должна появиться запись:

Т.к. вы только учитесь, то можете пока не использовать git. В итоге приложение весит довольно много (в текущей версии почти 250МБ):

Запускаем приложение React

Для того, чтобы запустить приложение, необходимо перейти в директорию D:\#NodeJS#\react_app\hello_react\ и запустить команду:

После того, как приложение запустится, вы получите сообщение в консоли:

И откроется в браузере страница http://localhost:3000/:

Краткое описание файлов в приложении React JS

Если мы перейдем в директорию нашего приложения React D:\#NodeJS#\react_app\hello_react , то мы увидим следующую структуру:

Общая конфигурация проекта React описана в package.json. Вот как это выглядит:

В файле находятся следующие атрибуты:

  • name — представляет имя приложения, которое было передано в create-response-app.
  • version — показывает текущую версию.
  • dependencies — список всех необходимых модулей / версий для нашего приложения. По умолчанию npm устанавливает самую последнюю основную версию.
  • devDependencies — перечисляет все модули / версии для запуска приложения в среде разработки.
  • scripts — список всех псевдонимов, которые могут использоваться для эффективного доступа к командам react-scripts. Например, если мы запустим npm build в командной строке, он выполнит внутреннюю «react-scripts build« .

Рассмотрим структуру каталога приложения:

  • Каталог node_modules предназначен для инструментов сборки. Файл package.json в корне приложения определяет, какие библиотеки будут установлены в node_modules при запуске npm install. После сборки приложения (финальная стадия разработки) этот каталог не публикуется в продуктив. Этот каталог добавляется в .gitignore
  • Все динамические компоненты будут расположены в каталоге src . В этой директории содержится код проекта (вся логика вашего приложения). Именно с ней вам придется большую часть времени работать. Рассмотрим файлы в каталоге src:
    • App.js — основной JS-компонент. Каждый компонент, который вы создаете в своем проекте, будет потомком этого компонента.
    • App.css — это таблица стилей для css правил. Приложение create-react-app предварительно настроено для использования css таблиц стилей. Также можно использовать scss файлы, просто установив node-sass модуль.
    • index.js — точка входа для нашего приложения. Этот файл импортирует код приложения из App.js компонента и делает его в root DIV, расположенном в index.html в public папке.
    • index.css — это вторичный css файл с общими данными шрифтов, которые можно удалить или использовать для глобального кода CSS.
    • App.test.js и setupTests.js — сборка исходного прилоежния поставляется с предварительно сконфигурированными jest и react-testing-library . В этот setupTest.js файл вы можете включить свои тестовые конфигурации, и App.test.js является основным тестовым файлом. Вы также можете безопасно удалить оба этих файла, если у вас нет опыта в тестировании.
    • manifest.json — этот файл используется для описания нашего приложения.
    • favicon.ico — это файл изображения значка, используемый в нашем проекте. Он также связан внутри index.html и manifest.json.
    • index.html — базовая HTML страница, является корневой для вашего проекта. Ее практически не придется исправлять, но она является также ключевой частью проекта.

    Сборка проекта React JS APP

    Забегая немножко вперед, опишем как создается сборка проекта. После изменения приложения React и его отладки запускается команда:

    Результат работы команды:

    В результате у нас появится директория build:

    В директории сборки весь код компилируется и минифицируется до наименьшего полезного состояния. Читаемость кода неважна, поскольку этот код не предназначен для чтения человеком.

    Деплой/Deploy проекта на Heroku (развертывание приложения React)

    Для того, чтобы задеплоить весь проект с автоматическим развертыванием приложения React без учета собранного проекта, необходимо скачать Heroku CLI:

    Инсталлируем скаченный дистрибутив. Далее в консоли запускаем команду:

    Откроется сайт, где нужно нажать кнопку Login (Enter your Heroku credentials)

    Также у вас должен быть инсталлирован git, если нет, то скачайте на сайте https://git-scm.com/ и установите.

    Далее последовательно запускаем команды:

    Откроется сайт (проект вашего приложения на React JS). Я свой пример переделал и у меня выводится сообщение текстовое:

    Далее можете внести на своей машине изменения в код App.js, например,

    И повторить команды:

    В таком виде проект соберется на стороне heroku.

    Что такое JSX?

    JSX — синтаксический сахар для функции React.createElement(component, props, . children) .

    JSX — это расширение React, которое позволяет нам писать JavaScript, который выглядит как HTML.

    JSX позволяет нам писать элементы HTML на JavaScript и размещать их в DOM без вызова методов createElement() , либо appendChild() . JSX преобразует HTML-теги в элементы React. Не обязательно использовать JSX при разработке React, но рекомендуется.

    С JSX вы можете писать выражения внутри фигурных скобок < >.

    JSX — это, по сути, компромисс . Вместо того, чтобы писать компоненты React с использованием React.createElement синтаксиса, мы используем синтаксис, очень похожий на HTML, а затем используем компилятор для преобразования его в React.createElement вызовы. Компилятор, переводящий одну форму синтаксиса в другую, известен как «транспилятор».

    Важно помнить при создании компонентов React, что Вы не пишете HTML. Вы используете расширение JavaScript для возврата вызовов функций, которые создают элементы React (которые по сути являются объектами JavaScript).

    Быстрый курс 2020 React JS от Владилена Минина

    Жизненный цикл React-компонента

    Диаграмму жизненного цикла React-компонента можно посмотреть на сайте:

    React Lifecycle Methods Diagram на русском:

    или на английском:

    Есть еще такая картинка:

    Краткое описание жизненного цикла

    Все, что вы видите в приложении React, является компонентом или частью компонента. В React компоненты созданы так, чтобы следовать естественному жизненному циклу. Они создаются (creation), развиваются (updating) и, наконец, умирают (deletion). Это называется жизненным циклом компонента.

    Компоненты React — это независимые и повторно используемые блоки кода. Они служат той же цели, что и функции JavaScript, но работают изолированно и возвращают HTML через функцию render(). Компоненты бывают двух типов: компоненты класса и компоненты функции. Их я опишу потом.

    Для каждого этапа жизненного цикла компонента, React предоставляет доступ к определенным встроенным событиям / методам, называемым перехватчиками жизненного цикла (lifecycle hooks) или методами жизненного цикла (lifecycle methods). Эти методы дают вам возможность контролировать и управлять тем, как компонент реагирует на изменения в приложении.

    Рассмотрим три фазы жизненного цикла компонента React: Mounting, Updating иUnmounting.

    Важно помнить, что render() это единственный метод, который требуется в компонентах React.

    Что такое Mounting?

    Mounting (монтирование) — означает размещение элементов в DOM.

    В React есть четыре встроенных метода, которые вызываются в указанном порядке при монтировании компонента:

    1. constructor()
    2. getDerivedStateFromProps() — вызывается прямо перед рендерингом элементаов в DOM.
    3. render() — выводит HTML в DOM.
    4. componentDidMount() — вызывается после рендеринга компонента. Вы можете использовать этот метод для настройки любых длительно выполняющихся процессов или асинхронных процессов, таких как выборка и обновление данных.

    Метод render() является обязательным и будет вызываться всегда, остальные необязательны и будут вызываться, если вы их определите.

    Метод constructor

    Метод constructor() вызывается раньше всего, когда компонент запускается, и это естественное место для установки initial state и других начальных значений.

    Метод constructor() вызывается с props , в качестве аргументов, и вы всегда должны начинать с вызова super(props) перед любым другим, это инициирует родительский метод конструктора и позволяет компоненту наследовать методы от своего родителя ( React.Component ).

    Пример:

    Компонент — это JS-класс. Как и любой класс, у него есть метод constructor , который вызывается React каждый раз, когда вы создаете компонент. Обычно он устанавливает состояние и свойства.

    Что такое Updating?

    Следующим этапом жизненного цикла является обновление компонента (Updating).

    Компонент обновляется всякий раз, когда происходит изменение состояния или свойств компонента.

    В React есть пять встроенных методов, которые вызываются в следующем порядке при обновлении компонента:

    1. getDerivedStateFromProps()
    2. shouldComponentUpdate()
    3. render()
    4. getSnapshotBeforeUpdate()
    5. componentDidUpdate()

    Метод render() является обязательным и будет вызываться всегда, остальные необязательны и будут вызываться, если вы их определите.

    Что такое Unmounting?

    Следующая фаза в жизненном цикле — это когда компонент удаляется из DOM или размонтируется (unmounting).

    В React есть только один встроенный метод, который вызывается при размонтировании компонента:

    • componentWillUnmount()

    state

    Компоненты React имеют встроенный state объект.

    В state объекте хранятся значения свойств, принадлежащих компоненту.

    Когда state объект изменяется, компонент перерисовывается.

    Объект state инициализируется в конструкторе:

    componentWillMount — этот метод устарел

    ComponentWillMount() раньше был методом жизненного цикла и вызывался непосредственно перед методом render() . React отказался от его использования из-за того, что он часто используется небезопасно.

    componentDidMount

    Метод жизненного цикла componentDidMount() запускается сразу после завершения метода render() и подключения компонента к DOM. Это лучшее место для запуска асинхронной функции. Вот базовый пример того, как вы можете получить данные в компоненте класса:

    componentDidUpdate

    Если у вас есть состояние, основанное на props, вам может потребоваться использовать componentDidUpdate() метод, который вызывается сразу после обновления. Используйте его для обновления модели DOM, сравнивая предыдущие свойства с текущими, см. Пример ниже:

    props и propTypes

    Props — это список атрибутов, передаваемые в компоненты React. Свойства передаются компонентам через атрибуты HTML.

    Компонент функции React получает этот список в качестве своего первого аргумента. Список передается как объект с ключами, представляющими имена атрибутов, и значениями, представляющими присвоенные им значения.

    Чтобы отправить props в компонент, используйте тот же синтаксис, что и атрибуты HTML:

    Добавьте атрибут «brand» к элементу Car:

    React — это все о компонентах

    В React мы описываем пользовательские интерфейсы с помощью компонентов, которые можно использовать повторно, компоновать и сохранять состояние.

    Мы определяем маленькие компоненты, а затем собираем их вместе, чтобы сформировать более крупные. Все компоненты, маленькие или большие, можно использовать повторно, даже в разных проектах.

    Вы можете думать о компонентах как о простых функциях (на любом языке программирования). Мы вызываем функции с некоторым input, и они дают нам некоторый output. Мы можем повторно использовать функции по мере необходимости и составлять более крупные функции из более мелких.

    Компоненты React точно такие же:

    • их входные данные — это набор «свойств»,
    • а их выходные данные — это описание пользовательского интерфейса.

    Компонент React — это шаблон. План. Глобальное определение. Это может быть функция или класс (с методом рендеринга).

    Мы можем повторно использовать один компонент в нескольких пользовательских интерфейсах, а компоненты могут содержать другие компоненты. Базовая форма компонента React — это на самом деле старая обычная функция JavaScript.

    Некоторые компоненты React чистые, но вы также можете добавить в компонент побочные эффекты. Например, компонент может изменить HTML-заголовок веб-страницы, когда он монтируется в браузере, или он может прокручивать представление браузера в определенное положение.

    Что наиболее важно, компонент React может иметь private state для хранения данных, которые могут изменяться в течение жизненного цикла компонента. Это private state является неявной частью ввода, которая управляет выводом компонента, и именно это и дало React название!

    Почему React вообще называется «React»?

    Когда состояние компонента React (который является частью его ввода) изменяется, пользовательский интерфейс, который он представляет (его вывод), также изменяется. Это изменение в описании пользовательского интерфейса должно быть отражено на устройстве,с которым мы работаем. В браузере нам нужно обновить дерево DOM. В приложении React мы не делаем этого вручную. React просто отреагирует на изменения состояния и автоматически (и эффективно) обновит DOM при необходимости.

    Что такое hook?

    Hook (или хук) в компоненте React — это вызов специальной функции. Все функции хуков начинаются со слова «use». Некоторые из них могут использоваться для обеспечения функционального компонента с элементами с отслеживанием состояния (например, useState ), другие могут использоваться для управляемых побочных эффектов (например, useEffect ) или для кэширования / запоминания функций и объектов (например, useCallback ). Hooks очень мощные, и когда дело доходит до вещей, которые вы можете с ними делать, нет предела.

    Функции hook React могут использоваться только в функциональных компонентах. Вы не можете использовать их в компонентах класса.

    Чтобы увидеть пример базовой useState hook, давайте заставим Button компонент реагировать на событие щелчка. Давайте сохраним количество нажатий на нее в переменной «count» и отобразим значение этой переменной как метку кнопки, которую она отображает.

    Tutorial: Intro to React

    Try the new React documentation.

    The updated Tutorial teaches modern React and includes live examples.

    The new docs will soon replace this site, which will be archived. Provide feedback.

    This tutorial doesn’t assume any existing React knowledge.

    Before We Start the Tutorial

    We will build a small game during this tutorial. You might be tempted to skip it because you’re not building games — but give it a chance. The techniques you’ll learn in the tutorial are fundamental to building any React app, and mastering it will give you a deep understanding of React.

    Tip

    This tutorial is designed for people who prefer to learn by doing. If you prefer learning concepts from the ground up, check out our step-by-step guide. You might find this tutorial and the guide complementary to each other.

    The tutorial is divided into several sections:

      will give you a starting point to follow the tutorial. will teach you the fundamentals of React: components, props, and state. will teach you the most common techniques in React development. will give you a deeper insight into the unique strengths of React.

    You don’t have to complete all of the sections at once to get the value out of this tutorial. Try to get as far as you can — even if it’s one or two sections.

    What Are We Building?

    In this tutorial, we’ll show how to build an interactive tic-tac-toe game with React.

    You can see what we’ll be building here: Final Result. If the code doesn’t make sense to you, or if you are unfamiliar with the code’s syntax, don’t worry! The goal of this tutorial is to help you understand React and its syntax.

    We recommend that you check out the tic-tac-toe game before continuing with the tutorial. One of the features that you’ll notice is that there is a numbered list to the right of the game’s board. This list gives you a history of all of the moves that have occurred in the game, and it is updated as the game progresses.

    You can close the tic-tac-toe game once you’re familiar with it. We’ll be starting from a simpler template in this tutorial. Our next step is to set you up so that you can start building the game.

    We’ll assume that you have some familiarity with HTML and JavaScript, but you should be able to follow along even if you’re coming from a different programming language. We’ll also assume that you’re familiar with programming concepts like functions, objects, arrays, and to a lesser extent, classes.

    If you need to review JavaScript, we recommend reading this guide. Note that we’re also using some features from ES6 — a recent version of JavaScript. In this tutorial, we’re using arrow functions, classes, let , and const statements. You can use the Babel REPL to check what ES6 code compiles to.

    Setup for the Tutorial

    There are two ways to complete this tutorial: you can either write the code in your browser, or you can set up a local development environment on your computer.

    Setup Option 1: Write Code in the Browser

    This is the quickest way to get started!

    First, open this Starter Code in a new tab. The new tab should display an empty tic-tac-toe game board and React code. We will be editing the React code in this tutorial.

    You can now skip the second setup option, and go to the Overview section to get an overview of React.

    Setup Option 2: Local Development Environment

    This is completely optional and not required for this tutorial!

    Optional: Instructions for following along locally using your preferred text editor

    This setup requires more work but allows you to complete the tutorial using an editor of your choice. Here are the steps to follow:

    1. Make sure you have a recent version of Node.js installed.
    2. Follow the installation instructions for Create React App to make a new project.
    1. Delete all files in the src/ folder of the new project

    Note:

    Don’t delete the entire src folder, just the original source files inside it. We’ll replace the default source files with examples for this project in the next step.

    1. Add a file named index.css in the src/ folder with this CSS code.
    2. Add a file named index.js in the src/ folder with this JS code.
    3. Add these three lines to the top of index.js in the src/ folder:

    Now if you run npm start in the project folder and open http://localhost:3000 in the browser, you should see an empty tic-tac-toe field.

    We recommend following these instructions to configure syntax highlighting for your editor.

    If you get stuck, check out the community support resources. In particular, Reactiflux Chat is a great way to get help quickly. If you don’t receive an answer, or if you remain stuck, please file an issue, and we’ll help you out.

    Now that you’re set up, let’s get an overview of React!

    React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

    React has a few different kinds of components, but we’ll start with React.Component subclasses:

    We’ll get to the funny XML-like tags soon. We use components to tell React what we want to see on the screen. When our data changes, React will efficiently update and re-render our components.

    Here, ShoppingList is a React component class, or React component type. A component takes in parameters, called props (short for “properties”), and returns a hierarchy of views to display via the render method.

    The render method returns a description of what you want to see on the screen. React takes the description and displays the result. In particular, render returns a React element, which is a lightweight description of what to render. Most React developers use a special syntax called “JSX” which makes these structures easier to write. The <div /> syntax is transformed at build time to React.createElement(‘div’) . The example above is equivalent to:

    If you’re curious, createElement() is described in more detail in the API reference, but we won’t be using it in this tutorial. Instead, we will keep using JSX.

    JSX comes with the full power of JavaScript. You can put any JavaScript expressions within braces inside JSX. Each React element is a JavaScript object that you can store in a variable or pass around in your program.

    The ShoppingList component above only renders built-in DOM components like <div /> and <li /> . But you can compose and render custom React components too. For example, we can now refer to the whole shopping list by writing <ShoppingList /> . Each React component is encapsulated and can operate independently; this allows you to build complex UIs from simple components.

    Inspecting the Starter Code

    If you’re going to work on the tutorial in your browser, open this code in a new tab: Starter Code. If you’re going to work on the tutorial locally, instead open src/index.js in your project folder (you have already touched this file during the setup).

    This Starter Code is the base of what we’re building. We’ve provided the CSS styling so that you only need to focus on learning React and programming the tic-tac-toe game.

    By inspecting the code, you’ll notice that we have three React components:

    • Square
    • Board
    • Game

    The Square component renders a single <button> and the Board renders 9 squares. The Game component renders a board with placeholder values which we’ll modify later. There are currently no interactive components.

    Passing Data Through Props

    To get our feet wet, let’s try passing some data from our Board component to our Square component.

    We strongly recommend typing code by hand as you’re working through the tutorial and not using copy/paste. This will help you develop muscle memory and a stronger understanding.

    In Board’s renderSquare method, change the code to pass a prop called value to the Square:

    Change Square’s render method to show that value by replacing with :

    React Devtools

    After: You should see a number in each square in the rendered output.

    React Devtools

    Congratulations! You’ve just “passed a prop” from a parent Board component to a child Square component. Passing props is how information flows in React apps, from parents to children.

    Making an Interactive Component

    Let’s fill the Square component with an “X” when we click it. First, change the button tag that is returned from the Square component’s render() function to this:

    If you click on a Square now, you should see ‘click’ in your browser’s devtools console.

    Note

    To save typing and avoid the confusing behavior of this , we will use the arrow function syntax for event handlers here and further below:

    Notice how with onClick= <() =>console.log(‘click’)> , we’re passing a function as the onClick prop. React will only call this function after a click. Forgetting () => and writing onClick= is a common mistake, and would fire every time the component re-renders.

    As a next step, we want the Square component to “remember” that it got clicked, and fill it with an “X” mark. To “remember” things, components use state.

    React components can have state by setting this.state in their constructors. this.state should be considered as private to a React component that it’s defined in. Let’s store the current value of the Square in this.state , and change it when the Square is clicked.

    First, we’ll add a constructor to the class to initialize the state:

    Note

    In JavaScript classes, you need to always call super when defining the constructor of a subclass. All React component classes that have a constructor should start with a super(props) call.

    Now we’ll change the Square’s render method to display the current state’s value when clicked:

    • Replace this.props.value with this.state.value inside the <button> tag.
    • Replace the onClick= <. >event handler with onClick= <() =>this.setState()> .
    • Put the className and onClick props on separate lines for better readability.

    After these changes, the <button> tag that is returned by the Square’s render method looks like this:

    By calling this.setState from an onClick handler in the Square’s render method, we tell React to re-render that Square whenever its <button> is clicked. After the update, the Square’s this.state.value will be ‘X’ , so we’ll see the X on the game board. If you click on any Square, an X should show up.

    When you call setState in a component, React automatically updates the child components inside of it too.

    The React Devtools extension for Chrome and Firefox lets you inspect a React component tree with your browser’s developer tools.

    React Devtools

    The React DevTools let you check the props and the state of your React components.

    After installing React DevTools, you can right-click on any element on the page, click “Inspect” to open the developer tools, and the React tabs (“⚛️ Components” and “⚛️ Profiler”) will appear as the last tabs to the right. Use “⚛️ Components” to inspect the component tree.

    However, note there are a few extra steps to get it working with CodePen:

    1. Log in or register and confirm your email (required to prevent spam).
    2. Click the “Fork” button.
    3. Click “Change View” and then choose “Debug mode”.
    4. In the new tab that opens, the devtools should now have a React tab.

    Completing the Game

    We now have the basic building blocks for our tic-tac-toe game. To have a complete game, we now need to alternate placing “X”s and “O”s on the board, and we need a way to determine a winner.

    Lifting State Up

    Currently, each Square component maintains the game’s state. To check for a winner, we’ll maintain the value of each of the 9 squares in one location.

    We may think that Board should just ask each Square for the Square’s state. Although this approach is possible in React, we discourage it because the code becomes difficult to understand, susceptible to bugs, and hard to refactor. Instead, the best approach is to store the game’s state in the parent Board component instead of in each Square. The Board component can tell each Square what to display by passing a prop, just like we did when we passed a number to each Square.

    To collect data from multiple children, or to have two child components communicate with each other, you need to declare the shared state in their parent component instead. The parent component can pass the state back down to the children by using props; this keeps the child components in sync with each other and with the parent component.

    Lifting state into a parent component is common when React components are refactored — let’s take this opportunity to try it out.

    Add a constructor to the Board and set the Board’s initial state to contain an array of 9 nulls corresponding to the 9 squares:

    When we fill the board in later, the this.state.squares array will look something like this:

    The Board’s renderSquare method currently looks like this:

    In the beginning, we passed the value prop down from the Board to show numbers from 0 to 8 in every Square. In a different previous step, we replaced the numbers with an “X” mark determined by Square’s own state. This is why Square currently ignores the value prop passed to it by the Board.

    We will now use the prop passing mechanism again. We will modify the Board to instruct each individual Square about its current value ( ‘X’ , ‘O’ , or null ). We have already defined the squares array in the Board’s constructor, and we will modify the Board’s renderSquare method to read from it:

    Each Square will now receive a value prop that will either be ‘X’ , ‘O’ , or null for empty squares.

    Next, we need to change what happens when a Square is clicked. The Board component now maintains which squares are filled. We need to create a way for the Square to update the Board’s state. Since state is considered to be private to a component that defines it, we cannot update the Board’s state directly from Square.

    Instead, we’ll pass down a function from the Board to the Square, and we’ll have Square call that function when a square is clicked. We’ll change the renderSquare method in Board to:

    Note

    We split the returned element into multiple lines for readability, and added parentheses so that JavaScript doesn’t insert a semicolon after return and break our code.

    Now we’re passing down two props from Board to Square: value and onClick . The onClick prop is a function that Square can call when clicked. We’ll make the following changes to Square:

    • Replace this.state.value with this.props.value in Square’s render method
    • Replace this.setState() with this.props.onClick() in Square’s render method
    • Delete the constructor from Square because Square no longer keeps track of the game’s state

    After these changes, the Square component looks like this:

    When a Square is clicked, the onClick function provided by the Board is called. Here’s a review of how this is achieved:

    1. The onClick prop on the built-in DOM <button> component tells React to set up a click event listener.
    2. When the button is clicked, React will call the onClick event handler that is defined in Square’s render() method.
    3. This event handler calls this.props.onClick() . The Square’s onClick prop was specified by the Board.
    4. Since the Board passed onClick= <() =>this.handleClick(i)> to Square, the Square calls the Board’s handleClick(i) when clicked.
    5. We have not defined the handleClick() method yet, so our code crashes. If you click a square now, you should see a red error screen saying something like “this.handleClick is not a function”.

    Note

    The DOM <button> element’s onClick attribute has a special meaning to React because it is a built-in component. For custom components like Square, the naming is up to you. We could give any name to the Square’s onClick prop or Board’s handleClick method, and the code would work the same. In React, it’s conventional to use on[Event] names for props which represent events and handle[Event] for the methods which handle the events.

    When we try to click a Square, we should get an error because we haven’t defined handleClick yet. We’ll now add handleClick to the Board class:

    After these changes, we’re again able to click on the Squares to fill them, the same as we had before. However, now the state is stored in the Board component instead of the individual Square components. When the Board’s state changes, the Square components re-render automatically. Keeping the state of all squares in the Board component will allow it to determine the winner in the future.

    Since the Square components no longer maintain state, the Square components receive values from the Board component and inform the Board component when they’re clicked. In React terms, the Square components are now controlled components. The Board has full control over them.

    Note how in handleClick , we call .slice() to create a copy of the squares array to modify instead of modifying the existing array. We will explain why we create a copy of the squares array in the next section.

    Why Immutability Is Important

    In the previous code example, we suggested that you create a copy of the squares array using the slice() method instead of modifying the existing array. We’ll now discuss immutability and why immutability is important to learn.

    There are generally two approaches to changing data. The first approach is to mutate the data by directly changing the data’s values. The second approach is to replace the data with a new copy which has the desired changes.

    Data Change with Mutation

    Data Change without Mutation

    The end result is the same but by not mutating (or changing the underlying data) directly, we gain several benefits described below.

    Complex Features Become Simple

    Immutability makes complex features much easier to implement. Later in this tutorial, we will implement a “time travel” feature that allows us to review the tic-tac-toe game’s history and “jump back” to previous moves. This functionality isn’t specific to games — an ability to undo and redo certain actions is a common requirement in applications. Avoiding direct data mutation lets us keep previous versions of the game’s history intact, and reuse them later.

    Detecting changes in mutable objects is difficult because they are modified directly. This detection requires the mutable object to be compared to previous copies of itself and the entire object tree to be traversed.

    Detecting changes in immutable objects is considerably easier. If the immutable object that is being referenced is different than the previous one, then the object has changed.

    Determining When to Re-Render in React

    The main benefit of immutability is that it helps you build pure components in React. Immutable data can easily determine if changes have been made, which helps to determine when a component requires re-rendering.

    You can learn more about shouldComponentUpdate() and how you can build pure components by reading Optimizing Performance.

    We’ll now change the Square to be a function component.

    In React, function components are a simpler way to write components that only contain a render method and don’t have their own state. Instead of defining a class which extends React.Component , we can write a function that takes props as input and returns what should be rendered. Function components are less tedious to write than classes, and many components can be expressed this way.

    Replace the Square class with this function:

    We have changed this.props to props both times it appears.

    Note

    When we modified the Square to be a function component, we also changed onClick= <() =>this.props.onClick()> to a shorter onClick= (note the lack of parentheses on both sides).

    We now need to fix an obvious defect in our tic-tac-toe game: the “O”s cannot be marked on the board.

    We’ll set the first move to be “X” by default. We can set this default by modifying the initial state in our Board constructor:

    Each time a player moves, xIsNext (a boolean) will be flipped to determine which player goes next and the game’s state will be saved. We’ll update the Board’s handleClick function to flip the value of xIsNext :

    With this change, “X”s and “O”s can take turns. Try it!

    Let’s also change the “status” text in Board’s render so that it displays which player has the next turn:

    After applying these changes, you should have this Board component:

    Declaring a Winner

    Now that we show which player’s turn is next, we should also show when the game is won and there are no more turns to make. Copy this helper function and paste it at the end of the file:

    Given an array of 9 squares, this function will check for a winner and return ‘X’ , ‘O’ , or null as appropriate.

    We will call calculateWinner(squares) in the Board’s render function to check if a player has won. If a player has won, we can display text such as “Winner: X” or “Winner: O”. We’ll replace the status declaration in Board’s render function with this code:

    We can now change the Board’s handleClick function to return early by ignoring a click if someone has won the game or if a Square is already filled:

    Congratulations! You now have a working tic-tac-toe game. And you’ve just learned the basics of React too. So you’re probably the real winner here.

    Adding Time Travel

    As a final exercise, let’s make it possible to “go back in time” to the previous moves in the game.

    Storing a History of Moves

    If we mutated the squares array, implementing time travel would be very difficult.

    However, we used slice() to create a new copy of the squares array after every move, and treated it as immutable. This will allow us to store every past version of the squares array, and navigate between the turns that have already happened.

    We’ll store the past squares arrays in another array called history . The history array represents all board states, from the first to the last move, and has a shape like this:

    Now we need to decide which component should own the history state.

    Lifting State Up, Again

    We’ll want the top-level Game component to display a list of past moves. It will need access to the history to do that, so we will place the history state in the top-level Game component.

    Placing the history state into the Game component lets us remove the squares state from its child Board component. Just like we “lifted state up” from the Square component into the Board component, we are now lifting it up from the Board into the top-level Game component. This gives the Game component full control over the Board’s data, and lets it instruct the Board to render previous turns from the history .

    First, we’ll set up the initial state for the Game component within its constructor:

    Next, we’ll have the Board component receive squares and onClick props from the Game component. Since we now have a single click handler in Board for many Squares, we’ll need to pass the location of each Square into the onClick handler to indicate which Square was clicked. Here are the required steps to transform the Board component:

    • Delete the constructor in Board.
    • Replace this.state.squares[i] with this.props.squares[i] in Board’s renderSquare .
    • Replace this.handleClick(i) with this.props.onClick(i) in Board’s renderSquare .

    The Board component now looks like this:

    We’ll update the Game component’s render function to use the most recent history entry to determine and display the game’s status:

    Since the Game component is now rendering the game’s status, we can remove the corresponding code from the Board’s render method. After refactoring, the Board’s render function looks like this:

    Finally, we need to move the handleClick method from the Board component to the Game component. We also need to modify handleClick because the Game component’s state is structured differently. Within the Game’s handleClick method, we concatenate new history entries onto history .

    Note

    Unlike the array push() method you might be more familiar with, the concat() method doesn’t mutate the original array, so we prefer it.

    At this point, the Board component only needs the renderSquare and render methods. The game’s state and the handleClick method should be in the Game component.

    Showing the Past Moves

    Since we are recording the tic-tac-toe game’s history, we can now display it to the player as a list of past moves.

    We learned earlier that React elements are first-class JavaScript objects; we can pass them around in our applications. To render multiple items in React, we can use an array of React elements.

    In JavaScript, arrays have a map() method that is commonly used for mapping data to other data, for example:

    Using the map method, we can map our history of moves to React elements representing buttons on the screen, and display a list of buttons to “jump” to past moves.

    Let’s map over the history in the Game’s render method:

    As we iterate through history array, step variable refers to the current history element value, and move refers to the current history element index. We are only interested in move here, hence step is not getting assigned to anything.

    For each move in the tic-tac-toe game’s history, we create a list item <li> which contains a button <button> . The button has a onClick handler which calls a method called this.jumpTo() . We haven’t implemented the jumpTo() method yet. For now, we should see a list of the moves that have occurred in the game and a warning in the developer tools console that says:

    Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of “Game”.

    Let’s discuss what the above warning means.

    When we render a list, React stores some information about each rendered list item. When we update a list, React needs to determine what has changed. We could have added, removed, re-arranged, or updated the list’s items.

    Imagine transitioning from

    In addition to the updated counts, a human reading this would probably say that we swapped Alexa and Ben’s ordering and inserted Claudia between Alexa and Ben. However, React is a computer program and does not know what we intended. Because React cannot know our intentions, we need to specify a key property for each list item to differentiate each list item from its siblings. One option would be to use the strings alexa , ben , claudia . If we were displaying data from a database, Alexa, Ben, and Claudia’s database IDs could be used as keys.

    When a list is re-rendered, React takes each list item’s key and searches the previous list’s items for a matching key. If the current list has a key that didn’t exist before, React creates a component. If the current list is missing a key that existed in the previous list, React destroys the previous component. If two keys match, the corresponding component is moved. Keys tell React about the identity of each component which allows React to maintain state between re-renders. If a component’s key changes, the component will be destroyed and re-created with a new state.

    key is a special and reserved property in React (along with ref , a more advanced feature). When an element is created, React extracts the key property and stores the key directly on the returned element. Even though key may look like it belongs in props , key cannot be referenced using this.props.key . React automatically uses key to decide which components to update. A component cannot inquire about its key .

    It’s strongly recommended that you assign proper keys whenever you build dynamic lists. If you don’t have an appropriate key, you may want to consider restructuring your data so that you do.

    If no key is specified, React will present a warning and use the array index as a key by default. Using the array index as a key is problematic when trying to re-order a list’s items or inserting/removing list items. Explicitly passing key= silences the warning but has the same problems as array indices and is not recommended in most cases.

    Keys do not need to be globally unique; they only need to be unique between components and their siblings.

    Implementing Time Travel

    In the tic-tac-toe game’s history, each past move has a unique ID associated with it: it’s the sequential number of the move. The moves are never re-ordered, deleted, or inserted in the middle, so it’s safe to use the move index as a key.

    In the Game component’s render method, we can add the key as <li key=> and React’s warning about keys should disappear:

    Clicking any of the list item’s buttons throws an error because the jumpTo method is undefined. Before we implement jumpTo , we’ll add stepNumber to the Game component’s state to indicate which step we’re currently viewing.

    First, add stepNumber: 0 to the initial state in Game’s constructor :

    Next, we’ll define the jumpTo method in Game to update that stepNumber . We also set xIsNext to true if the number that we’re changing stepNumber to is even:

    Notice in jumpTo method, we haven’t updated history property of the state. That is because state updates are merged or in more simple words React will update only the properties mentioned in setState method leaving the remaining state as is. For more info see the documentation.

    We will now make a few changes to the Game’s handleClick method which fires when you click on a square.

    The stepNumber state we’ve added reflects the move displayed to the user now. After we make a new move, we need to update stepNumber by adding stepNumber: history.length as part of the this.setState argument. This ensures we don’t get stuck showing the same move after a new one has been made.

    We will also replace reading this.state.history with this.state.history.slice(0, this.state.stepNumber + 1) . This ensures that if we “go back in time” and then make a new move from that point, we throw away all the “future” history that would now be incorrect.

    Finally, we will modify the Game component’s render method from always rendering the last move to rendering the currently selected move according to stepNumber :

    If we click on any step in the game’s history, the tic-tac-toe board should immediately update to show what the board looked like after that step occurred.

    Congratulations! You’ve created a tic-tac-toe game that:

    • Lets you play tic-tac-toe,
    • Indicates when a player has won the game,
    • Stores a game’s history as a game progresses,
    • Allows players to review a game’s history and see previous versions of a game’s board.

    Nice work! We hope you now feel like you have a decent grasp of how React works.

    Check out the final result here: Final Result.

    If you have extra time or want to practice your new React skills, here are some ideas for improvements that you could make to the tic-tac-toe game which are listed in order of increasing difficulty:

    Installing Node and npm

    Getting React up and running is not as simple as downloading one large piece of software. You will need to install many, smaller software packages.

    The first thing to install is a good installer! You need a way to download and install software packages easily, without having to worry about dependencies.

    In other words, you need a good package manager. We’ll be using a popular package manager named npm. npm is a great way to download, install, and keep track of JavaScript software.

    You can install npm by installing Node.js . Node.js is an environment for developing server-side applications. When you install Node.js , npm will install automatically.

      to navigate to the Node.js homepage in a new tab.
    1. You should see links to download Node.js . Click on the download link of your choice. Follow the subsequent instructions to install Node.js and npm . If you've already installed Node.js , that's okay, do it anyway.

    Congratulations! You’ve just installed some incredibly powerful software!

    How npm is Different

    When you install software, you may be used to something like this: you install what you need, it sits there on your computer, and you can use it whenever you want.

    You can do that with npm ! But there's a different, better way: install what you need, over and over again, every time that you need it. Download and install React every time that you make a React app.

    That sounds much worse! Here’s why it’s actually better:

    First, npm makes installation extremely easy. Installing software over and over sounds like a headache, but it really isn't. We'll walk through how soon!

    Second, npm modules ("modules" are another name for software that you download via npm ) are usually small. There are countless modules for different specific purposes. Instead of starting your app with a giant framework that includes tons of code you don't need, you can install only modules that you will actually use! This helps keep your code quick, easy to navigate, and not vulnerable to dependencies that you don't understand.

    IN CONCLUSION: Starting now, every step in this article series will be a step that you have to take every time you make a new React app. You don’t have to install Node.js and npm anymore, but you should start from here for every new React project that you make.

    npm init

    Alright, let’s make a React app on your home computer! Where do you start?

    To begin, decide where you want to save your app, and what you want to name it. In the terminal, cd to wherever you want to save your app. Use mkdir to make a new directory with your app's name. cd into your new directory.

    Once you’ve done all that, type this command into your terminal:

    You will get a lot of prompts! You can answer them, but it’s also safe to just keep hitting return and not worry about it.

    Once the prompts are done, use your favorite text editor to open all of the files in your project’s root directory. You could do this with a terminal command such as atom . or subl . . You will see that a new file named package.json has been created!

    What just happened?

    The command npm init automatically creates a new file named package.json . package.json contains metadata about your new project.

    Soon, you will install more npm modules. package.json keeps track of the modules that you install. Other developers can look at your package.json file, easily install the same modules that you've installed, and run their own local versions of your project! This is fantastic for collaborating.

    Install React

    Alright! You’ve made a project folder, navigated into it, and used npm init to create a package.json file. Now you're ready to install some modules!

    To install a module using npm , you need to know that module's name. If you want to install a module and you aren't sure of its exact name, you can search for it here. Our first module is named react .

    To install the react module, type this command in the terminal:

    install can be abbreviated as i , and —save can be abbreviated as -S , if you like to abbreviate:

    You just installed React! Now you can access it in your files with the code var React = require('react') .

    Install ReactDOM

    If you look at package.json , you can see that there's an object named dependencies that now has react listed as a dependency. This indicates that your project is "dependent" on having react installed. If someone tries to run your project, it probably won't work unless they install react first.

    You can also see something else new in your directory: a folder named node_modules .

    node_modules is where npm modules are saved. If you open node_modules , you should see a folder named react , which contains the code that makes React run.

    The next thing that you want to install is react-dom . Once you install react-dom , you will be able access it in your files with the code var ReactDOM = require('react-dom') .

    To install react-dom , type one of these two commands in the terminal:

    Part:II

    Background

    Before React code can run in the browser, it must be changed in certain ways. One necessary transformation is compiling JSX into vanilla JavaScript.

    Install Babel

    Babel is a JavaScript compiler that includes the ability to compile JSX into regular JavaScript. Babel can also do many other powerful things. It's worth exploring outside of the context of this course!

    Babel 's npm module's name is babel-core . You're going to install babel-core slightly differently than you installed react and react-dom . Instead of npm install —save babel-core , you will use the command npm install —save-dev babel-core .

    This is because you will only be using Babel in development mode. When a React app is shipped into production, it no longer needs to make transformations: the transformations will be hard-coded in place. The —save-dev flag saves an npm module for development version only.

    Just as —save can be shortened to -S , —save-dev can be shortened to -D .

    You’re also going to install two other babel-related modules, named babel-loader and babel-preset-react , respectively. We'll explain those soon!

    Use one of these terminal commands to install babel-core , babel-loader , and babel-preset-react :

    Configure Babel

    In order to make Babel work, you need to write a babel configuration file.

    In your root directory, create a new file named .babelrc. If you get prompted about starting a filename with a period, go ahead and say that it’s okay.

    Save the following code inside of .babelrc:

    That’s it! Babel is now ready to go.

    Part:III

    em in which your React app will automatically run through Babel and compile your JSX, before reaching the browser.

    Also, JSX to JavaScript is just one of many transformations that will need to happen to your React code. You need to set up a “transformation manager” that will take your code and run it through all of the transformations that you need, in the right order. How do you make that happen?

    There are a lot of different software packages that can make this happen. The most popular as of this writing is a program called webpack .

    Install webpack

    webpack is a module that can be installed with npm , just like react and react-dom . You'll also be installing two webpack-related modules named webpack-dev-server and html-webpack-plugin , respectively. We'll explain these a little more soon.

    webpack should be saved in development mode, just like babel .

    Install webpack , webpack-dev-server , and html-webpack-plugin with one of these two terminal commands:

    webpack.config.js

    Alright! Webpack has been installed!

    Webpack’s job is to run your React code through various transformations. Webpack needs to know exactly what transformations it should use!

    You can set that information by making a special webpack configuration file. This file must be located in the outermost layer of your root directory, and must be named webpack.config.js. It is where you will put all of the details required to make webpack operate.

    In your root directory, create a new file named webpack.config.js.

    Configure webpack

    Webpack is going to take your JavaScript, run it through some transformations, and create a new, transformed JavaScript file. This file will be the ones that the browser actually reads.

    In order to do this, Webpack needs to know three things:

    1. What JavaScript file it should transform.
    2. Which transformations it should use on that file.
    3. Where the new, transformed file should go.

    Let’s walk through those three steps!

    First, in webpack.config.js, write:

    All of webpack’s configuration will go inside of that object literal!.

    What JavaScript File Should Webpack Transform?

    The first thing that webpack needs to know is an entry point. The entry point is the file that Webpack will transform.

    Your entry point should be the outermost component class of your React project. It might look something like this:

    In this example, webpack will transform the result of <App /> . If <App /> 's render function contains components from other files, then those components will be transformed as well. If you make your entry point the outermost component class of your app, then webpack will transform your entire app!

    To specify an entry point, give module.exports a property named entry . entry 's value can be a filepath, or an array of filepaths if you would like to have more than one entry point. For this project, you will only need one.

    In webpack.config.js, update module.exports to look like this:

    In Node.js , __dirname refers to the currently executing file. __dirname + /app/index.js will create a filepath pointing to the currently executing file, down into a folder named app , and landing on a file named index.js .

    What Transformations Should Webpack Perform?

    Webpack can now successfully grab your outermost component class file, and therefore grab your entire React app. Now that webpack can grab all of this code, you need to explain what webpack should do with it once it’s been grabbed.

    You can tell webpack what to do with the code that it’s grabbed by adding a second property to module.exports . This property should have a name of module and a value of an object literal containing a loaders array:

    Each “loader” that you add to the loaders array will represent a transformation that your code will go through before reaching the browser.

    Write a Loader

    Each loader transformation should be written as an object literal. Here’s your first loader, empty for now:

    Each loader object needs a property called test . The test property specifies which files will be affected by the loader:

    The regular expression /\.js$/ represents all strings that end with the pattern, ".js". That means that this loader will perform a transformation on all ".js" files.

    In addition to “test”, each loader transformation can have a property named include or exclude . You can use "exclude" to specify files that match the "test" criteria, that you don't want to be transformed. Similarly you can use "include" to specify files that don't fit the "test" criteria, that you do want to be transformed:

    The node_modules folder contains lots of JavaScript files that will be caught by your /\.js$/ test. However, you don't want anything in the node_modules folder to be transformed. node_modules holds the code for React itself, along with the other modules that you've downloaded. You don't want to transform that!

    The final property of each loader is what transformation that loader should perform! You specify a particular transformation with a property named loader :

    In this example, you have a loader with three properties: test , exclude , and loader . Your loader will search for all files ending in ".js", excluding files in the node_modules folder. Whatever files it finds, it will run through the 'babel-loader' transformation.

    Where does the string 'babel-loader' come from? When you ran the command npm install —save-dev babel-core babel-loader babel-preset-react , you installed babel-loader into your node_modules folder. Your loader property will automatically be able to find it there. The magic of npm !

    Add babel-loader to webpack.config.js.

    What Should Webpack Do With The Transformed JavaScript?

    Alright! Now you have told webpack which files to grab, and how to transform those files. Webpack will grab your React app and run it through babel-loader, translating all of your JSX into JavaScript.

    The final question is, where should the transformed JavaScript go?

    Answer this by adding another property to module.exports . This property should have a name of output , and a value of an object:

    The output object should have two properties: filename and path . filename will be the name of the new, transformed JavaScript file. path will be the filepath to where that transformed JavaScript file ends up:

    This will save your transformed JavaScript into a new file named build/transformed.js.

    Part:IV

    HTMLWebpackPlugin

    Good work! The hardest part is over. There is, however, still one issue.

    Your app’s main HTML file is named app/index.html. Your app’s outermost JavaScript file, which is also your entry point for webpack, is named app/index.js. These two files are neighbors, both living in the app folder.

    Before webpack performs its transformations, your entry file (app/index.js) and your HTML file (app/index.html) are located in the same directory. The HTML file contains a link to the entry file, looking something like this: <script src="./index.js"></script> .

    After webpack performs its transformations, your new entry file will be located in build/transformed.js, and that link won’t work anymore!

    When webpack makes a new JavaScript file, it needs to make a new HTML file as well. There is a tool for this, and you’ve already installed it: html-webpack-plugin .

    Configure HTMLWebpackPlugin

    At the top of webpack.config.js, add this line of code:

    When you call require('html-webpack-plugin') , the returned value is a constructor function. Most of the work of configuring HTMLWebpackPlugin should be done on an instance of that constructor function.

    Add this new declaration, underneath the previous one:

    The HTMLWebpackPlugin Configuration Object

    That empty configuration object is where you will tell HTMLWebpackPlugin what it needs to know.

    The object’s first property should be named template . template 's value should be a filepath to the current HTML file, the one that you're trying to copy and move:

    The object’s second property should be named filename . filename 's value should be the name of the newly created HTML file. It's fine to name it index.html . Since the new HTML file will be located in the build folder, there won't be any naming conflicts:

    The object’s final property should be named inject . inject value should be be a string: either 'head' or 'body' .

    When HTMLWebpackPlugin creates a new HTML file, that new HTML file will contain a <script> tag linking to webpack's new JavaScript file. This <script> tag can appear in either the HTML file's <head> or <body> . You choose which one via the inject property.

    Here’s an full example:

    The Plugins Property

    You have fully configured your HTMLWebpackPlugin instance! Now all that's left is to add that instance to module.exports .

    You can do this by creating a new module.exports property named plugins . plugins value should be an array, containing your configured HTMLWebpackPlugin instance!

    Find the plugins property at the bottom of module.exports :

    Part:V

    npm scripts

    Great work! You’ve installed and configured Node, npm, React, ReactDOM, Babel, and Webpack. That’s all of the installation that you need!

    To make these installed parts actually run, you will be using npm command-line scripts. You’ve already used some of these, such as npm init and npm install —save react .

    You will find that as your applications become more complex, you will need to use more and more verbose command-line scripts. This can become a serious pain!

    Fortunately, npm scripts are here to help.

    Inside of your package.json file, find the scripts object. This object lets you give your command-line scripts easier names, and look them up whenever you forget them!

    Let’s say that you need to use the script npm run build && npm run git-commit && npm run git-push . That's way too much to remember. In package.json, you could add:

    After that, you only need to type npm run deploy , and it will execute the command saved as deploy 's value. And even better, you can look up the command in package.json if you forget.

    In package.json, replace the scripts object with this:

    npm run build will make webpack perform its transformations.

    npm run start will start a local server! npm run start will also give you the ability to change your app and see the changes automatically, without having to restart the server for each new change.

    Run a Local React App

    Inside of your root directory, create a new directory named app . Create two new files inside of app : app/index.js and app/index.html.

    In app/index.html, copy the following code:

    In app/index.js, copy the following code:

    Inside of the app folder, create a new folder named components . Create a new file inside of app/components named app/components/App.js.

    In app/components/App.js, write a component class. This component class can render whatever you want. Don’t forget to require React at the top of the file, and to set module.exports equal to your component class at the bottom of the file.

    In the terminal, type:

    Check for a newly created build folder inside of your root directory. The build folder should contain new html and js files: build/index.html and build/transformed.js.

    In the terminal, type:

    Open a new browser tab and navigate to http://localhost:8080 . See your React component shining gloriously in the sun.

    In app/components/App.js, make a change to your component class’s render function. Refresh the browser tab and see your change appear on the screen!

    The Condensed Version

    That seems like an enormous amount of work to get a simple app up and running!

    Perhaps it was, but that was in large part due to the fact that we slowly explained every step. Executing the steps by rote is much faster.

    Here’s a condensed version of how to get a React app up and running:

    In the terminal, create a new directory. cd into that directory.

    Type the following command-line scripts:

    • npm init
    • npm i -S
    • npm i -D babel- babel-preset-react
    • npm i -D webpack webpack-dev-server html-webpack-plugin

    In your root directory, create a file named .babelrc. Write this inside:

    In your root directory, create another file named webpack.config.js. Write (or copy) this inside:

    In package.json, replace the scripts object with this:

    Create a directory inside of your root directory named app , and another directory inside of app named app/components .

    Читать:
    Как вставить название картинки в ворде

Похожие статьи