Npx create react app windows

Create React App Build & Test PRs Welcome

Logo

Create React apps with no build configuration.

  • Creating an App – How to create a new app.
  • User Guide – How to develop apps bootstrapped with Create React App.

Create React App works on macOS, Windows, and Linux.
If something doesn’t work, please file an issue.
If you have questions or need help, please ask in GitHub Discussions.

Quick Overview

npx create-react-app my-app
cd my-app
npm start

If you’ve previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

Then open http://localhost:3000/ to see your app.
When you’re ready to deploy to production, create a minified bundle with npm run build.

npm start

Get Started Immediately

You don’t need to install or configure tools like webpack or Babel.
They are preconfigured and hidden so that you can focus on the code.

Create a project, and you’re good to go.

Creating an App

You’ll need to have Node 14.0.0 or later version on your local development machine (but it’s not required on the server). We recommend using the latest LTS version. You can use nvm (macOS/Linux) or nvm-windows to switch Node versions between different projects.

To create a new app, you may choose one of the following methods:

npx

npx create-react-app my-app

(npx is a package runner tool that comes with npm 5.2+ and higher, see instructions for older npm versions)

npm

npm init react-app my-app

npm init <initializer> is available in npm 6+

Yarn

yarn create react-app my-app

yarn create <starter-kit-package> is available in Yarn 0.25+

It will create a directory called my-app inside the current folder.
Inside that directory, it will generate the initial project structure and install the transitive dependencies:

my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── serviceWorker.js
    └── setupTests.js

No configuration or complicated folder structures, only the files you need to build your app.
Once the installation is done, you can open your project folder:

Inside the newly created project, you can run some built-in commands:

npm start or yarn start

Runs the app in development mode.
Open http://localhost:3000 to view it in the browser.

The page will automatically reload if you make changes to the code.
You will see the build errors and lint warnings in the console.

Build errors

npm test or yarn test

Runs the test watcher in an interactive mode.
By default, runs tests related to files changed since the last commit.

Read more about testing.

npm run build or yarn build

Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.

Your app is ready to be deployed.

User Guide

You can find detailed instructions on using Create React App and many tips in its documentation.

How to Update to New Versions?

Please refer to the User Guide for this and other information.

Philosophy

  • One Dependency: There is only one build dependency. It uses webpack, Babel, ESLint, and other amazing projects, but provides a cohesive curated experience on top of them.

  • No Configuration Required: You don’t need to configure anything. A reasonably good configuration of both development and production builds is handled for you so you can focus on writing code.

  • No Lock-In: You can “eject” to a custom setup at any time. Run a single command, and all the configuration and build dependencies will be moved directly into your project, so you can pick up right where you left off.

What’s Included?

Your environment will have everything you need to build a modern single-page React app:

  • React, JSX, ES6, TypeScript and Flow syntax support.
  • Language extras beyond ES6 like the object spread operator.
  • Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  • A fast interactive unit test runner with built-in support for coverage reporting.
  • A live development server that warns about common mistakes.
  • A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
  • An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria. (Note: Using the service worker is opt-in as of react-scripts@2.0.0 and higher)
  • Hassle-free updates for the above tools with a single dependency.

Check out this guide for an overview of how these tools fit together.

The tradeoff is that these tools are preconfigured to work in a specific way. If your project needs more customization, you can «eject» and customize it, but then you will need to maintain this configuration.

Popular Alternatives

Create React App is a great fit for:

  • Learning React in a comfortable and feature-rich development environment.
  • Starting new single-page React applications.
  • Creating examples with React for your libraries and components.

Here are a few common cases where you might want to try something else:

  • If you want to try React without hundreds of transitive build tool dependencies, consider using a single HTML file or an online sandbox instead.

  • If you need to integrate React code with a server-side template framework like Rails, Django or Symfony, or if you’re not building a single-page app, consider using nwb, or Neutrino which are more flexible. For Rails specifically, you can use Rails Webpacker. For Symfony, try Symfony’s webpack Encore.

  • If you need to publish a React component, nwb can also do this, as well as Neutrino’s react-components preset.

  • If you want to do server rendering with React and Node.js, check out Next.js or Razzle. Create React App is agnostic of the backend, and only produces static HTML/JS/CSS bundles.

  • If your website is mostly static (for example, a portfolio or a blog), consider using Gatsby or Next.js. Unlike Create React App, Gatsby pre-renders the website into HTML at build time. Next.js supports both server rendering and pre-rendering.

  • Finally, if you need more customization, check out Neutrino and its React preset.

All of the above tools can work with little to no configuration.

If you prefer configuring the build yourself, follow this guide.

React Native

Looking for something similar, but for React Native?
Check out Expo CLI.

Contributing

We’d love to have your helping hand on create-react-app! See CONTRIBUTING.md for more information on what we’re looking for and how to get started.

Supporting Create React App

Create React App is a community maintained project and all contributors are volunteers. If you’d like to support the future development of Create React App then please consider donating to our Open Collective.

Credits

This project exists thanks to all the people who contribute.

Thanks to Netlify for hosting our documentation.

Acknowledgements

We are grateful to the authors of existing related projects for their ideas and collaboration:

  • @eanplatter
  • @insin
  • @mxstbr

License

Create React App is open source software licensed as MIT. The Create React App logo is licensed under a Creative Commons Attribution 4.0 International license.

React is one of the popular JavaScript libraries for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. In this article, we will discuss the steps to install React on Windows 10.

React can be used as a base for the development of single-page or mobile applications. It is a powerful library to deal with complex projects in an easy manner.

React Native, one of the most lovable hybrid mobile application development frameworks is also based on React.

Here I am going to explain the installation and set up of a React App on Windows 10 platform. As React is a library, we can start using it inside our project just by importing it.

But here we are going to install the create-react-app tool(a tool built for us to create react applications) and build a react app using it on Windows 10 Operating System.

For visual learners, the video below will help you to do this installation faster. It is completely based on this blog post.

For others, please follow the below steps to install React on Windows 10.

Prerequisites

To continue with this article, the reader must know the basics of working with the Command Prompt/ Powershell in a Windows 10 system.

What we will learn?

Here in this article, we will learn the following things:-

  • Install Node.js on a Windows 10 system
  • Creating a new React project using create-react-app tool
  • Running the React app we created

Install Nodejs

Node.js actually provides a runtime environment to execute JavaScript code from outside a browser. NPM, the default package manager for Nodejs is used for managing and sharing the packages for any JavaScript project. React uses Node.js and NPM for the management of dependencies and runtime.

In this tutorial, we are going to install the create-react-app tool using the Node Package Manager(NPM). Create-react-app is a tool developed by the React.js team that makes React’s setting up easier.

So first, it needs to install Nodejs on our system. NPM will be installed with Nodejs. The current stable version of Node.js can be downloaded and installed from the official website that is given below.

https://nodejs.org

Download the latest version and install it. Here we can choose the LTS or the latest version. Because both of the version supports React.

After the installation, check the versions using the below commands.

node -v
npm -v

This will show the installed versions of Node.js and NPM.

Note:- If you are really a beginner in this field, the guide Steps to install Node.js and NPM on Windows 10 will help you.

Create a New React Project

After the successful installation of Nodejs and NPM, we can create a new React project by temporarily installing the create-react-app tool. Execute the below command on the Command prompt window.

npx create-react-app awesome-project

Here NPX will temporarily install create-react-app and create a new react project named awesome-project. Note that the awesome-project is the name I have chosen for my react project.

Running the Application

So the app we created can run locally on our system with the npm start command.

cd awesome-project
npm start

This will open up the react application in a new tab of our browser with the below URL.

http://localhost:3000

Note:- If port 3000 is busy with another process, the app will start in port 3001 or any other port available.

Note: We recommend using Visual Studio code as the source-code editor for working with React projects.

Summary

So, in this article, we have discussed the steps to Install React on a Windows 10 system. These steps are verified by our team and 100% working.

В этой статье изучим, как с помощью инструмента Create React App создать новое одностраничное приложение на React. После этого подробно разберём файловую структуру созданного проекта и команды для управления им.

Инструмент Create React App

Для полноценного создания пользовательских интерфейсов на React или каком-нибудь другом инструменте перед веб-разработчиком в большинстве случаев стоит задача в выборе необходимых средств для этого (webpack, Babel, ESLint, и т.д.) и корректной их настройки.

К счастью, разработчики React подготовили для нас готовый инструмент, который позволяет всё это сделать автоматически. Называется он Create React App.

Официальный сайт инструмента Create React App

Итак, Create React App (сокращенно CRA) – это инструмент, который позволяет нам настроить среду для создания одностраничных веб-приложений на основе React, посредством выполнения всего одной команды. Также можно отметить, что этот инструмент официально поддерживается командой React.

Одностраничное приложение (Single Page Application или сокращённо SPA) – это приложение, содержащее всего одну единственную HTML-страницу, контент которой динамически обновляется с помощью JavaScript. Т.е. SPA состоит из одной страницы, контент для которой загружается и изменяется посредством JavaScript без её полной перезагрузки.

Это программа имеет открытый исходный код и расположена она на Github.

Требования

Чтобы использовать Create React App, необходимо убедиться, что у вас на компьютере установлена программа Node.js.

Для проверки её наличия, можно запросить версию:

node -v

Получение версии Node.js, установленной на локальном компьютере

Для разработки на локальном компьютере необходим «Node.js» версии не ниже 14 и npm не ниже 5.6. При установке «Node.js» также устанавливает программу npm.

npm (сокращенно от Node Package Manager) – это пакетный менеджер, который позволяет нам устанавливать и удалять JavaScript пакеты, управлять их версиями и зависимостями. Проверить установленную версию npm можно так:

npm -v

Получение версии npm, установленной на локальном компьютере

В качестве альтернативы вы можете использовать пакетный менеджер Yarn. Yarn – это инструмент аналогичный npm, т.е. он также предназначен для установки пакетов и управления ими. Причём он их берёт из того же репозитория, что npm.

Чтобы использовать Yarn, его необходимо установить:

npm install -g yarn

Создание нового React-приложения

Для создания нового проекта посредством create-react-app необходимо перейти в нужную папку и ввести в терминале следующую команду:

# через npm
npx create-react-app my-app
# через yarn
yarn create react-app my-app

npx – это инструмент, который появился в npm, начиная с версии 5.2.0. С его помощью мы можем, например, запустить пакет create-react-app без необходимости его глобальной установки:

npm install -g create-react-app

Команда npx create-react-app my-app создаст нам новое React-приложение.

В результате у нас появится каталог внутри текущей папки и в нём все необходимые файлы. В данном случае каталог my-app. Он будет содержать всё необходимое для разработки этого проекта на React.

Откроем только что созданный проект в редакторе коде, например, Visual Studio Code, и рассмотрим его структуру.

Структура проекта на React, сгенерированного с помощью инструмента create-react-app

Структура проекта

В корне проекта расположены следующие файлы и папки:

node_modules/
public/
src/
.gitignore
package-lock.json
package.json
README.md
  • node-modules – это папка, которая содержит пакеты (зависимости), которые требуются нашему приложению. Их загружает и обновляет npm.
  • public – это папка, в которой находится страница index.html, определяющая HTML шаблон всего нашего приложения; кроме этого она ещё содержит некоторые другие файлы для нашего приложения (favicon.ico, manifest.json, robots.txt и т.д.), а также в неё при необходимости можно поместить любые другие файлы, которые должны быть скопированы в папку build нетронутыми, т.е. без обработки их с помощью webpack.
  • src (сокращенно от source) – каталог, содержащий исходный код приложения. Разработка проекта практически ведётся здесь.
  • .gitignore – нужен для скрытия файлов и папок от системы контроля версий GIT. Этот файл содержит все необходимые записи, каким-то определённым образом его настраивать не нужно.
  • package.json – это набор метаданных о вашем приложении: название проекта, версия, пакеты от которых зависит проект и т.д. package.json является ключевым файлом для любых приложений, основанных на Node.js.
  • package-lock.json – файл, который создаёт npm автоматически при установке зависимостей. Он содержит в себе полную информацию обо всех установленных зависимостях, включая их точные версии. Кроме package-lock.json у вас может быть ещё yarn.lock, если вы используете Yarn для установки пакетов.
  • README.md — это краткая справочное руководство по использованию инструмента create-react-app.

В файле package.json в ключе dependencies перечислены зависимости, т.е. библиотеки, которые необходимы приложению. Среди основных:

  • react и react-dom – ядро проекта на React (в предыдущей теме мы их подключали через CDN);
  • react-scripts – набор скриптов, которые используются для разработки, сборки и тестирования приложения. Они выполняют настройку среды разработки, запуск сервера с живой перезагрузкой, подключают необходимые зависимости, модули и т.д.

Команды для управления проектом

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

1. Запуск проекта. Осуществляется с помощью команды start:

npm start

Эту команду можно ввести прямо в терминале Visual Studio Code, если вы его используете в качестве текстового редактора:

Структура проекта на React, сгенерированного с помощью инструмента create-react-app

Эта команда запускает приложение в режиме разработки. В результате запускается сервер и открывается браузер с адресом http://localhost:3000, в котором показывается рабочее React-приложение. При внесении изменения в код, страница автоматически перезагружается. Все ошибки и предупреждения выводятся в консоль.

Запуск React-приложения в режиме разработки и отображение его в браузере

2. Сборка приложения:

npm run build

Эту команду обычно запускают после завершения разработки проекта. Она выполняет сборку приложения из исходных файлов для продакшена. Полученные оптимизированные файлы помещаются в папку build и они отвечают за функционал всего приложения. После сборки вы можете приступать к развертыванию приложения.

3. Запуск тестов:

npm test

4. Команда, которая позволяет извлечь все файлы конфигурации и зависимости непосредственно в проект:

npm run eject

Эту команду можно ввести только один раз. После этого поддержание всей этой конфигурации и сценариев вы выполняете самостоятельно. Обычно это используется, когда вы хотите настроить конфигурацию проекта так как вам это нужно.

Содержимое папки public

В папке public находятся:

  • favicon.ico, logo192.png, logo512.png – иконки;
  • index.html – HTML шаблон страницы;
  • manifest.json – манифест веб-приложения;
  • robots.txt – текстовый файл, который содержит указания для роботов поисковых систем;

Кроме этого, в эту папку можно поместить другие файлы, которые необходимо скопировать в каталог build нетронутыми (т.е. без обработки).

Чтобы ссылаться на ресурсы в public, необходимо использовать переменную с именем PUBLIC_URL:

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

При запуске npm run build инструмент Create React App заменит %PUBLIC_URL% правильным абсолютным путем, чтобы ваш проект работал, даже если вы используете маршрутизацию на стороне клиента или размещаете его по некорневому URL-адресу.

index.html

Инструмент create-react-app, как мы уже отмечали выше, выполняет генерацию проекта для разработки одностраничных приложений на React. В нём файл index.html как раз является той единственной страницей, которая будет входной для всего нашего приложения. Изменить название этого файла нельзя.

Содержимое файла index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

В этом файле устанавливаются некоторые базовые настройки для нашего приложения: язык, кодировка, favicon, viewport, заголовок, manifest, title, description и т.д.

С помощью тега <noscript> отображается контент на странице, который сообщает пользователю, что в браузере необходимо включить JavaScript для запуска этого приложения.

Но самое важное на что необходимо обратить внимание – это на тег <div id="root"></div>. Это корневой элемент, в который будет выводиться весь контент нашего приложения. Здесь нам необходимо запомнить его id, т.к. в JavaScript мы будем использовать его для получения этого элемента.

Как можете заметить здесь нет подключённых скриптов. Они будут добавляться инструментом create-react-app автоматически. Т.е. как-то самостоятельно их подключать здесь не нужно.

При необходимости вы можете в этом файле подключить другие ресурсы. Например, стили, шрифты и т.д. Но в большинстве случаев так делать не нужно, рекомендуется это выполнять в JavaScript через import.

manifest.json

manifest.json – это манифест, в котором описывается информация о веб-приложении. Он представляет собой текстовый файл, который в формате JSON содержит название приложения, некоторое количество иконок, стартовый URL, как оно будет выглядеть и некоторые другие параметры.

Содержимое файла manifest.json:

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

При этом манифест является частью веб-технологии, который называется PWA (сокращено от Progressive Web Apps). Этот файл позволяет установить PWA на главный экран смартфона, предоставляя пользователю более быстрый доступ к приложению.

Содержимое папки src

Папка src (сокращенно от source) – это место, в котором хранятся исходные коды разрабатываемого проекта и где веб-разработчик проводит почти всё время работая над ним.

В этой папке имеется файл index.js. Этому файлу нельзя изменять имя, т.к. он является точкой входа для JavaScript. Т.е. так же как public/index.html.

При необходимости вы можете удалить или переименовать другие файлы, но названия public/index.html и src/index.js в структуре проекта нужно оставить так как они есть.

index.js

Изначально файл src/index.js содержит следующий код:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Начинается файл с импорта модулей JavaScript и других ресурсов. import позволяют index.js использовать код, определенный в другом месте. На первой строчке импортируется библиотека React, а на второй – ReactDOM, которая предоставляет методы для взаимодействия с DOM или другими словами с HTML-страницей. Эти две библиотеки составляют ядро React.

Далее импортируются стили, которые применяются ко всему нашему приложению:

import './index.css';

Затем – React-компонент App из App.js:

import App from './App';

На следующей строчке – функция reportWebVitals, которая позволяет нам получить результаты производительности нашего приложения с использованием различных метрик. Для их измерения используется сторонняя библиотека web-vitals.

Например, для отправки результатов в консоль необходимо передать ссылку на метод console.log в качестве аргумента этой функции:

reportWebVitals(console.log);

После этого создаётся корень приложения посредством вызова метода ReactDOM.createRoot(), которому в качестве аргумента передаем DOM-элемент, который мы получили с помощью document.getElementById('root').

Затем выполняется рендеринг React-компонента <App /> в DOM:

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

React.StrictMode – это инструмент, который в данном случае включает строгий режим для всего приложения. Он упрощает определение потенциальных проблем в приложении.

React-компонент App

React-компонент App, который используется в src/index.js, находится в src/App.js. Этот компонент в данном случае представляет всё наше приложение, которое мы видим в браузере:

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Этот файл можно разделить на 3 основные части: импорт различных ресурсов, компонент App и инструкция export для экспортирования App.

C помощью import выполняется импорт логотипа из ./logo.svg и CSS, связанный с нашим компонентом.

Далее расположена простая функция с именем App. Эта функция используется для создания простого React-компонента, в данном случае App.

В самом низу файла инструкция export default App делает компонент App доступным для других модулей.

Компонент App

Код простого React-компонента:

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

В качестве результата с помощью оператора return эта функция возвращает React-элементы для отображения их на странице.

Именование React-компонентов осуществляется в стиле PascalCase. Т.е. их название всегда начинаются с заглавной буквы, а другие слова, которые являются частью его названия тоже начинаются с большой буквы. Не допускается пробелов, тире и других знаков, т.е. всё пишется слитно.

После return внутри круглых скобках мы описываем, по сути, HTML, который будет отображать этот компонент на странице. Но на самом деле это не HTML, а JSX – специальное расширение языка JavaScript, с помощью которого мы производим элементы.

Конструкция {logo} выводит значение переменной logo.

Изменение React-приложения

Изменим компонент App так, чтобы он выводил Hello, world!.

Для этого откроем файл src/App.js и заменим всё содержимое в return на <div className="App">Hello, world!</div>:

import './App.css';

function App() {
  return (
    <div className="App">Hello, world!</div>
  );
}

export default App;

Также удалим файлы с SVG-изображением logo.svg и файлы, связанные с тестами.

Содержимое файла App.css, отвечающего за стили компонента App, изменим на следующий код:

.App {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-size: 5rem;
}

После выполненных изменений, сохраним файлы App.css и App.js путём нажатия Ctrl+S и перейдём в браузер.

В браузере мы увидим изменённое приложение, причём даже без перезагрузки страницы благодаря функции горячей перезагрузки проекта:

Изменение React-приложения

If you are new to React and want to start building your own projects, then there is a helpful tool you can use.

Create React App makes it simple to get started coding in React because it comes with all of the starter files needed to build your projects.

But once you have React installed you might be wondering, «What are all of these files and folders?»

I had the exact same reaction when I first started using Create React App. So I decided to write a series of articles detailing everything that comes with Create React App.

In part 1, I will walk you through how to install React using Create React App and the command line.

  • What is Create React App?
  • What is the command line?
  • Checking for Node installation
  • Installing React using npx Create React App
  • Installing React using npm or Yarn
  • How to add React to an existing project using Create React App

What is Create React App?

Create React App is a quick way to get started creating single page React apps.

You don’t have to worry about how to configure webpack or babel. Create React App configures all of that for you.

Create React App only works for creating front end projects. If you need to add a backend component or database, then you will need to look into other technologies for that.

When you are done creating your React app, you can create an optimized build folder and deploy your project using something like Netlify.

What is the command line?

Before we can get started with creating a new React app, we need to understand how to access the command line.

The command line is a place where you can type out commands for the computer to execute. Some of these commands include creating new files/ folders and installing new technologies on your computer.

If you are on a Mac, you can access the command line by using the Spotlight Search to find the Terminal App. Here is a helpful walkthrough guide on how to find the Terminal app.

If you are on a Windows, you can access the command line by clicking the Start menu and typing in cmd. Here is a helpful walkthrough guide on how to access the command prompt for the different Windows versions.

Checking for Node installation

Before we get started, you will need to have Node version 10 or higher installed on your local machine.

If you are not sure if Node is installed, run this command in the command line.

node -v

Enter fullscreen mode

Exit fullscreen mode

If installed, then you should see a version number.

v16.10.0

Enter fullscreen mode

Exit fullscreen mode

If it does not come back with a version number, then you will need to install Node.

You can go to the official Node.js page to install Node on your local machine.

If you need more assistance installing Node.js, then please look into these helpful guides.

  • How to install Node on Mac
  • How to install Node on Windows

Installing React using npx Create React App

npx is a helpful tool you can use to download packages from the npm registry.

The first step is to go to the location on your computer where you want to create your new React app. I am going to create my new app on the Desktop.

Open up your command line and type in this command and hit enter. cd stands for change directory.

cd Desktop

Enter fullscreen mode

Exit fullscreen mode

You should see that you are now in the Desktop.

jessicawilkins@Dedrias-MacBook-Pro-2 Desktop % 

Enter fullscreen mode

Exit fullscreen mode

Then run this command in the command line and hit enter. This will create a new react project in the Desktop.

You can name your project whatever you want. I am going to name my project demo-react-app.

npx create-react-app demo-react-app

Enter fullscreen mode

Exit fullscreen mode

This process usually takes a few minutes. You should start to see these messages in the command line.

Creating a new React app in /Users/jessicawilkins/Desktop/demo-react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Enter fullscreen mode

Exit fullscreen mode

When the installation is complete you should see this message in the command line.

Success! Created demo-react-app at /Users/jessicawilkins/Desktop/demo-react-app

Enter fullscreen mode

Exit fullscreen mode

Then you need to type in cd followed by the name of your new React project.

cd demo-react-app

Enter fullscreen mode

Exit fullscreen mode

Then run npm start in the command line. That will start the local server and open up your new React app.

npm start

Enter fullscreen mode

Exit fullscreen mode

A new browser window will open at http://localhost:3000/.
You should see this result on the screen.

default react project

You should see this result in the command line.

Compiled successfully!

You can now view demo-react-app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.131:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

Enter fullscreen mode

Exit fullscreen mode

Congratulations! You have successfully created a new React application. 😃

To stop your local server, please use the keyboard command Ctrl+C in the command line.

Installing React using npm or Yarn

Installing using npm

The first step is to go to the location on your computer where you want to create your new React app. I am going to create my new app on the Desktop.

Open up your command line and type in this command and hit enter. cd stands for change directory.

cd Desktop

Enter fullscreen mode

Exit fullscreen mode

You should see that you are now in the Desktop.

jessicawilkins@Dedrias-MacBook-Pro-2 Desktop % 

Enter fullscreen mode

Exit fullscreen mode

Then run this command in the command line and hit enter. This command will only work if you have npm version 6 or higher.

You can choose to name your application whatever you like. I am going to name mine my-app.

npm init react-app my-app

Enter fullscreen mode

Exit fullscreen mode

This usually takes a few minutes but you should start to see these messages in the command line.

Creating a new React app in /Users/jessicawilkins/Desktop/my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Enter fullscreen mode

Exit fullscreen mode

When the installation is complete, change directory to the new project folder by running this command.

cd my-app

Enter fullscreen mode

Exit fullscreen mode

Then run npm start and hit enter.

A new browser window will open at http://localhost:3000/.
You should see this result on the screen.

default react project

To stop your local server, please use the keyboard command Ctrl+C in the command line.

Installing using Yarn

First check if Yarn is installed on your local machine by running this command in the command line and hitting enter.

yarn --version

Enter fullscreen mode

Exit fullscreen mode

If it is installed, then it will come back with a version number like this.

jessicawilkins@Dedrias-MacBook-Pro-2 ~ % yarn --version
1.22.17

Enter fullscreen mode

Exit fullscreen mode

If it does not come back with a version number, then you will need to install Yarn.

Please read through the detailed instructions on how to install Yarn on your local machine.

Then change directories to your Desktop folder using the command line.

Run this command in the command line and hit enter. This will only work if you have Yarn version .25 or higher.

You can choose to name your React app whatever you like. I am going to name mine my-app.

yarn create react-app my-app

Enter fullscreen mode

Exit fullscreen mode

You should start to see these messages in the command line.

yarn create v1.22.17
success Installed "create-react-app@4.0.3" with binaries:
      - create-react-app
[####################################################################] 68/68
Creating a new React app in /Users/jessicawilkins/Desktop/my-app.

Enter fullscreen mode

Exit fullscreen mode

Then run this command and hit enter.

 cd my-app

Enter fullscreen mode

Exit fullscreen mode

Then run yarn start which starts your local server for the new React application.

A new browser window will open at http://localhost:3000/.
You should see this result on the screen.

default react project

To stop your local server, please use the keyboard command Ctrl+C in the command line.

How to add React to an existing project using Create React App

You will first need to go to the location of your existing project folder. In this example, I am have a folder called example-folder located on the Desktop.

This is what the command would look like.

cd Desktop/example-folder

Enter fullscreen mode

Exit fullscreen mode

You should now see that you are in the project folder.

jessicawilkins@Dedrias-MacBook-Pro-2 example-folder % 

Enter fullscreen mode

Exit fullscreen mode

Then run this command if you are using npx and hit enter. The space and period at the end of the command are important because it tells the computer to create a new React application in that existing folder.

npx create-react-app .

Enter fullscreen mode

Exit fullscreen mode

Run this command if you are using npm and hit enter.

npm init react-app .

Enter fullscreen mode

Exit fullscreen mode

Run this command if you are using Yarn and hit enter.

yarn create react-app .

Enter fullscreen mode

Exit fullscreen mode

That is the whole process for creating a new React application using Create React App.

If you want to learn more about creating new React apps using templates or TypeScript, then please read through the detailed instructions from the documentation.

In part 2, we will learn about the following files and folders:

  • package.json
  • package-lock.json
  • README.md
  • node_modules

React has become an essential tool for modern web development, and getting it set up on your machine is the first step to start building amazing user interfaces.

It’s a popular JavaScript library for building UIs, focusing on performance and reusability, and has revolutionized web development by making it easier to create fast, responsive, and maintainable interfaces that really work for people.

Its component-based architecture and focus on how it performs in real-world settings have made it an attractive choice for developers looking to build modern web applications.

In this comprehensive guide, we’ll guide you through the process of installing React on Windows, macOS, and Linux operating systems. But first, let’s discuss the importance of React and how it can benefit your development workflow.

Onward!

What is React?

React homepage.

React

React is a powerful JavaScript library specifically designed for building user interfaces. It was developed by Jordan Walke, a software engineer at Facebook, in 2013.

React focuses on creating and managing UI components, which are reusable pieces of code that can manage their state and render UI elements. Its component-based architecture encourages developers to create modular and reusable components, reducing the amount of duplicate code and speeding up development time.

The use of a virtual DOM in React enhances rendering, resulting in faster and more efficient performance in comparison to traditional DOM manipulation techniques. This focus on performance and reusability has made React a popular choice among developers.

React has changed the game for web development. Don’t miss out — install it with this guide and give it a try 🤝Click to Tweet

Who Uses React?

React has gained popularity among a wide range of developers, as it provides a powerful and flexible way to build user interfaces for web applications. Here’s a look at some of the people who commonly use React:

  • Web Developers: They use React to create engaging and responsive user interfaces for websites and web applications. React’s component-based architecture allows them to build modular applications that are easier to maintain and update.
  • Front-end Developers: These developers use React to create user-facing components that interact with backend services and APIs. React simplifies the process of building complex user interfaces by breaking them down into smaller, more manageable components.
  • Full-stack Developers: Full-stack developers use React in conjunction with backend technologies like Node.js, Express, and MongoDB to build full-featured web applications. React’s flexibility makes it easy to integrate with various backend systems, streamlining the development process.

Many prominent companies in the tech industry also use React, showcasing its versatility and widespread adoption. Some examples of companies using React in their tech stack include:

  • Facebook: As the creator of React, Facebook uses it extensively throughout its web applications, including the main Facebook site, Instagram, and WhatsApp Web.
  • Airbnb: Airbnb uses React to build its user interfaces, allowing them to create a seamless and performant experience for its users across various platforms.
  • Netflix: Netflix employs React to create its web application, taking advantage of its performance optimizations and component-based architecture to deliver a smooth user experience.
  • Uber: Uber uses React to power its web applications, making it easier for them to create intuitive and responsive interfaces for its users.
  • Pinterest: Pinterest leverages React’s component-based architecture to build a visually stunning and highly interactive web application for users to discover and save creative ideas.
  • Reddit: Reddit utilizes React to develop its web application, providing a fast and engaging user experience for millions of users across the platform.
  • Dropbox: Dropbox takes advantage of React’s performance optimizations and component-based architecture to create a user-friendly and efficient web application for managing and sharing files.

By using React, these companies demonstrate the power and flexibility of this popular JavaScript library, making it an essential tool for modern web development.

Advantages of Using React

React offers several advantages that make it a popular choice for modern web development.

Here are some key benefits:

Component-Based Design Promotes Reusability

React’s architecture allows developers to create modular and reusable components, reducing code duplication and making it easier to maintain and update applications. This approach promotes consistency and simplifies the development process.

Virtual DOM for Improved Performance

React uses a virtual DOM to optimize rendering, making it faster and more efficient than traditional DOM manipulation. By only updating the parts of the DOM that have changed, React minimizes the time spent on rendering and improves overall application performance.

Strong Community Support

The React community is extensive and highly engaged in developing the technology. They regularly share their expertise through online platforms such as forums, social media, and blogs. This strong community support ensures that React continues to evolve and improve while also providing valuable resources for developers to learn from and troubleshoot issues.

Wide Range of Third-Party Libraries and Tools

The React ecosystem is vast, with a plethora of libraries and tools available to help developers build and optimize their applications. These resources can save time and effort by providing pre-built solutions and enhancements for common tasks and challenges.

Popular Choice for Modern Web Development

React has gained widespread adoption among developers and companies, making it a popular choice for building modern web applications. This popularity means that developers with React skills are in high demand, making it a valuable skill set to have in the job market.

React Prerequisites

Before diving into installing and using React, it’s essential to have some foundational knowledge and tools in place. Here are the prerequisites for getting started with React:

  • Basic knowledge of HTML, CSS, and JavaScript: Familiarity with these core web technologies is necessary for understanding how to build and style components in React.
  • Familiarity with command line/terminal: React development often involves using command line tools and interfaces, so it’s important to be comfortable navigating and executing commands in your system’s terminal or command prompt.
  • Node.js and npm installed: React relies on Node.js and npm (Node Package Manager) for managing dependencies and running build scripts. Make sure you have both installed on your system before proceeding with React installation.

System Requirements

Before installing React, it’s important to ensure your system meets the necessary requirements. Here’s what you need:

  • Operating System: Windows 10 or 11, macOS 10.10, or Ubuntu 16 are recommended for the best compatibility and performance.
  • Hardware: At least 4GB of RAM and 10GB of storage space are required to run React and its associated tools smoothly.
  • A web browser and Internet access: A modern web browser (such as Google Chrome, Mozilla Firefox, or Microsoft Edge) and Internet access are necessary for viewing and testing your React applications.
  • Node.js and npm installed: As mentioned earlier, React relies on Node.js and npm for managing dependencies and running build scripts. Make sure you have both installed on your system.

How To Install React

Each operating system has slightly different requirements when installing React. Follow along with the appropriate set of instructions below for the operating system you use.

How To Install React on Windows

In this section, we’ll guide you through the process of installing React on a Windows machine.

Follow these steps to get started:

  1. Install Node.js and npm
  2. Install Create React App
  3. Create a New React Project
  4. Go to the Project Directory and Start the Development Server

Step 1: Install Node.js and npm

Before installing React, you need to have Node.js and npm (Node Package Manager) installed on your system. If you haven’t already installed them, follow these steps:

  1. Visit the Node.js download page at: https://nodejs.org/en/download/
  2. Download the installer for your Windows system (either the LTS or Current version is fine, but the LTS version is recommended for most users)
  3. To install Node.js and npm, please run the installer and carefully follow the provided prompts.

Downloading the Node.Js installer for Windows. 

Downloading the Node.Js installer for Windows.

After the installation is complete, you can verify that Node.js and npm are installed by opening a command prompt and running the following commands:

node -v npm -v

These commands should display the version numbers for Node.js and npm, respectively.

Step 2: Install Create React App

Create React App is a command-line tool that simplifies the process of setting up a new React project with a recommended project structure and configuration. To install Create React App globally, open a command prompt and run the following command:

npm install -g create-react-app

This command installs Create React App on your system, making it available to use in any directory.

Step 3: Create a New React Project

Now that you have Create React App installed, you can use it to create a new React project. To do this, open a command prompt, go to the directory where you want the project to live, and run the following command:

create-react-app my-app

Replace “my-app” with the desired name for your project. Create React App will create a new directory with the specified name and generate a new React project with a recommended project structure and configuration.

Step 4: Go To the Project Directory and Start the Development Server

Once the project is created, head over to the project directory by running the following command in the command prompt:

cd my-app

Replace “my-app” with the name of your project directory. Now, start the development server by running the following command:

npm start

This command launches the development server, which watches for changes to your project files and automatically reloads the browser when changes are detected.

A new browser window should open with your React application running at http://localhost:3000/ that looks like this:

React has been successfully installed on Windows.

React has been successfully installed on Windows.

Congratulations! You have successfully installed React on your Windows machine and created a new React project. You can now begin building your user interfaces with React.

How To Install React on macOS

Now, let’s walk through the process of installing React on a computer running macOS:

  1. Install Node.js and npm
  2. Install Create React App On Your macOS
  3. Create a New React Project
  4. Go to the Project Directory and Start the Development Server

Step 1: Install Node.js and npm

As with the Windows installation process, you need to have Node.js and npm (Node Package Manager) installed on your macOS system as well. If you haven’t already installed them, follow these steps:

  1. Visit the Node.js download page
  2. Download the macOS installer

Downloading the Node.js installer for macOS.

Downloading the Node.js installer for macOS.
  1. Once downloaded, click the .pkg file in your Downloads folder to run the installer.
  2. Follow the instructions that appear on your screen, including accepting the License Agreement, selecting the target destination for the installed files, and selecting the installation type.

Follow the on-screen prompts to complete Node.js installation.

Follow the on-screen prompts to complete Node.js installation.

After the installation is complete, you can verify that Node.js and npm are installed by opening a terminal and running the following commands:

node -v
npm -v

These commands should display the version numbers for Node.js and npm, respectively.

Alternatively, you can install Node.js and npm via the command line. To do this, open Terminal then input:

brew install node

Wait for the installation to complete then verify its installation in the same way as above, by entering:

node -v

And then:

npm -v

Step 2: Install Create React App On Your macOS

Now, let’s get started with installing Create React App on macOS.

Create React App is a convenient way to set up a single-page application with minimal steps and no configuration.

Let’s proceed with the installation steps.

First, open the terminal and create a folder named react-app by typing the following command:

mkdir react-app

Next, navigate to the react-app directory with this command:

cd react-app

To verify that you’re in the correct directory, type the following command and press Enter:

pwd

Once you’ve confirmed that you’re in the right directory, you can create a new React project.

Step 3: Create a New React Project

Now that you have Create React App installed, you can use it to create a new React project. type the command below:

npx create-react-app my-app

npx is a module included with npm. The installation steps will take some time, so be patient.

Step 4: Go To the Project Directory and Start the Development Server

After the command has been executed successfully, navigate to the my-app directory:

cd my-app

Finally, type:

npm start

Upon successful execution of the command, your default web browser will open at

http://localhost:3000/:

You should see the React logo in your web browser following successful installation.

You should see the React logo in your web browser following successful installation.

And that’s it! React is now installed and ready to use on your macOS.

How To Install React on Linux

If you have a Linux-based system, you’ll want to follow this set of steps to install React:

  1. Install npm
  2. Install create-react-app utility
  3. Create and launch your first React application

Step 1: Install npm

Login to your server as a sudo user and run the following command:

sudo apt install npm

Once the installation is complete, verify the version of npm installed using the command:

npm --version

The installation of npm also installs Node.js. Confirm the version of Node installed using the command:

node --version

Step 2: Install create-react-app Utility

create-react-app is a utility that allows you to set up all the tools required for a React application.

It saves time and effort by setting everything up from scratch, giving you a head start.

To install the tool, run the following npm command:

sudo npm -g install create-react-app

Once installed, confirm the version of create-react-app by running:

create-react-app --version

Step 3: Create and Launch Your First React Application

Creating a React application is simple and straightforward. We will create a React app called my-app as follows:

create-react-app my-app

This process takes about 5 minutes to install all the packages, libraries, and tools needed by the application. Patience is key.

If the application was created successfully, you’ll receive a notification with the basic commands you can run to start managing the application.

To run the application, navigate into the app directory:

cd my-app

Then run the command:

npm start

You’ll see an output showing you how to access the application in the browser.

Open your browser and navigate to your server’s IP address:

http://server-ip:3000

And, as with the Windows and macOS installation processes, you should see the React logo in your browser:

You should see the React logo in your browser post-installation. 

You should see the React logo in your browser post-installation.

This demonstrates that the default React app is up and running.

You’ve now successfully installed React on Linux and created an application in React!

Why struggle with UI development when there’s an easier way? 😉 React’s components can help simplify the process, saving you time and effort! Get started with this guide 🤓Click to Tweet

Summary

Hopefully, you’ve found this guided through the process of installing React on Windows, macOS, and Linux helpful. We covered the prerequisites and system requirements needed to set up a React development environment, as well as the installation of Node.js and npm. We also demonstrated how to use the create-react-app utility to create a new React project and start a development server.

Now that you have React installed on your machine, it’s time to dive in and start following along with tutorials, learning best practices, and figuring out how to build amazing user interfaces. React’s design, performance perks, and strong community support make it an excellent choice for modern web development.

As you progress in your React journey, you might want to consider using Kinsta’s Application Hosting Service for your React projects. Kinsta provides a high-performance, scalable, and secure hosting platform that can help you get the most out of your React applications.

Good luck!

  • Nport windows driver manager это
  • Npas windows server 2019 что такое
  • Nport windows driver manager скачать
  • Npas windows 2016 что это
  • Np355v5c s0eru драйвера windows 10