Quick Summary: Create React App is a feature-rich development environment for learning React, and is the best method to start building a new single-page application in React. We can use create-react-app to bootstrap a React application on your preferred system. It offers a modern build setup with zero configuration.*
If you are a developer, we don't need to ask you what React is. Even if you are a newbie in the web development industry, you might have seen and heard of React for front-end development probably a lot of times. We assume that you have a basic understanding of the React library, usages, features, advantages, and disadvantages.
In case you wish to create a React app, allow us to clear your mind that creating a React project consists of a complicated multi-step process, a setup of a build system, base directory structure, and a code transpiler to convert modern syntax to code that is readable by all browsers.
Now you don’t have to worry about these processes as Create React App comes with all JavaScript packages (basic linting, testing, code transpiling, and build systems) required to build and run a React app.
Moreover, create-react-app has a hot reloading feature that will refresh your page as you change code during development. In a nutshell, it will help you create a background to start coding in just a few minutes by developing components and structure for your directories.
The Create React App is the easiest and quickest way to build large-scale React apps.
In this article, we are going to discuss the prerequisites to Create React App, what are the different ways to Create React App, how can we create React applications, and how to leverage all the features of Create React App. And we will answer the most commonly asked questions as well.
Moreover, we have also included some helpful tips we discovered while building React apps with Create React App to make your development workflow even easier.
React is a popular JavaScript framework used to build front-end applications. Developed by Facebook, React has made its strong presence in the dev community to build fast applications using an intuitive programming paradigm that ties JavaScript with an HTML-like syntax – JSX.
According to a recent survey by Statista, 39.5% of respondents reported using React.js for their development project. Also, you can expect the React.js market to value around USD 28.6 billion by 2027.
In short, ReactJs is a popular and widely used front-end library for developing single page applications. Since it’s a library, we can install this library to Create React App for developing single page applications.
Now, without any further ado, let’s understand what create-react-app is.
Create React App is one type of tool or generator for new developers, which allows them to develop and execute React projects. You don’t have to configure it manually. In other words, you don’t have to worry about the whole process of configuring a build system like Webpack.
This Create React App wraps all the required dependencies like Babel and Webpack for React project itself so that you can focus on coding the React app only. Moreover, Create React App offers an amazing developer experience, sets up the development environment, and optimizes the application for production.
One of the key advantages of using Create React App is its extensive documentation and community support, which can be invaluable for both beginners and experienced developers. Additionally, it simplifies the process of integrating third-party libraries and tools, making it easier to enhance your application’s functionality.
In fact, many different toolchains are used for various requirements when it comes to React development. For instance, Next.js is suitable for building sever-rendered websites and Gatsby is the best for static, content-oriented websites like blogs and newsletters.
You can find more information on Create React App GitHub account.
You are required to have the following things installed on your desktop:
If you wish to check the existing version of Node and NPM on your desktop, run the below-given command on your command prompt:
$ node –v
This command will help you check the version of the installed Node.
Now let’s run the given command to check the version of NPM.
$ npm -v
Now, is the time to get into the development mode to build a React app. Creating a React application using Create React App (CRA) is a straightforward process that streamlines the setup and configuration of a new React project. Let’s read all the steps carefully and understand them well and then execute them for the development.
For Create React App installation, you need to follow this step-by-step tutorial.
First, you need to open the command line to use create-react-app.
You can use npx
to create new React app.
npm version >= 5.2
Well, using npx, you can use create-react-app
package without installing first on your system. This is very convenient for newbie React developers.
Utilizing npx guarantees that we will be using the most recent Create React App version to create React project:
npx create-react-app my-first-react-app
The execution of the above command will help you create a folder name with “my-first-react-app” automatically on your system. And all the required packages will be installed, too.
Create React App comes up with some default templates to create React projects.
Let us explain it to you precisely. Suppose you are planning to create a React app with TypeScript. Then, you don’t need to install TypeScript manually. Create React App templates are there by default.
We can directly use the Create React App TypeScript template to create a react app with TypeScript.
npx create-react-app my-first-react-app --template typescript
After the installation of the required project files, your project structure may look something like this:
my-first-react-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
├── serviceWorker.js
└── setupTests.js
Now you must be wondering about the usage of these files and folders. Let's go through each folder now.
README.md
It is a markdown document with numerous links and useful advice that will assist you in using Create React App.
node_modules
It is a folder with all of Create React App's installed dependency-related code. There will not be any need to access this folder.
package.json
It oversees the node_modules
in our project and the scripts required to execute our app.
.gitignore
It is a file that tells Git not to monitor certain files and folders. Actually, we would not need any large folder, such as the node_modules folder.
public
Our React app's static assets, such as photos, svgs, and fonts, can be stored in a folder called public.
src
This folder has the source code and all React-related code. Eventually, we will work mostly on it to create a React project.
“Note: Every time you use Create React App to create a new React project, a new Git repository is created. Using git add
. and git commit -m "your commit message”
, you can begin saving changes to your app immediately.”
To run your React project, we need to open the command line. Go to the View option in VSCode and then click on Terminal.
Execute the below command to run a React project:
npm start
When we run create-react-app, we just have to run npm start in the app directory to start serving the development server. We will see a new browser opening with localhost:3000.
You will see something like the image below on the screen:
Any changes to the source code will be updated in real-time here. Let's see how that works.
Let’s minimize this existing terminal tab. Now, open src/App.js in your text editor.
You'll notice what appears to be a combination of HTML and JavaScript. This is JSX, the method used by React to add XML syntax to JavaScript. It offers a simple method for creating React components and compiling to JavaScript at runtime.
We'll go into more detail about this later on, but for now, let's make a quick change and view the result in the browser.
// 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;
Remove the p and a tags, and then add a h1 element with "Hello Radixweb” as the name of our app:
// 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" />
<h1>Hello Radixweb</h1>
</header>
</div>
);
}
export default App;
Now go back to your browser and see the update if you left the terminal open:
Congratulations!
You have finally made it to the React project successfully. You can add more features to your React app.
Did you notice something important? The development server automatically refreshes and reflects your changes to the browser.
You only have to refresh the browser manually while working with Create React App when you have an error.
It’s very easy and simple to test the React app using Create React App.
It has all the required packages to execute the test using React Testing Library. You will find many React Testing Library examples and React Testing Library tutorials on the internet.
For React Testing Library, @testing-library/react
is used.
The file App.test.js in the src directory has a simple test. It verifies that the link with the words "learn react" appears correctly when our App component is used.
We can run our tests with the given command:
npm run test
But if we run this, our test will fail.
This is because a title element has replaced the link element. We need a title element with the text "Hello Radixweb" in order to succeed in our test.
Note: All files with an ending in .test.js will undergo testing when the npm run test command executes.
// src/App.test.js
import { render, screen } from "@testing-library/react";
import App from "./App";
test("renders app title element", () => {
render(<App />);
const titleElement = screen.getByText(/Hello Radixweb/i);
expect(titleElement).toBeInTheDocument();
});
Again, running the test shows that it passes now:
PASS src/App.test.js
✓ renders app title element (54 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.776 s, estimated 3 s
Ran all test suites related to changed files.
Note: Here, you don't have to manually start and stop the test command when you execute it. If a test fails, you may go inside the app code, fix the issue, and save it. All tests will be run again successfully.
Now, we can see how our project works in the index.js file after the running test.
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
By attaching the package ReactDOM to an HTML element with the id value "root," ReactDOM renders our application (particularly, the App component and every component within it).
You may find this element at public/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" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
The div with the root id you see above is used to attach the entire React app to this HTML page.
There is nothing to be changed within the body
tags. However, it’s important to change the metadata in the head
tags to send signals to users and search engines about our specific app.
Well, it’s very useful from an SEO perspective. It has meta tags for a title, favicon image, and description.
In addition, you will also see some additional tags like theme-color, apple-touch-icon, and manifest. These are helpful if users wish to add your application to the computer's home screen.
In this case, we can modify the title to reflect the name of the app we're developing and the description to match:
<!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="Creating a React app with simple steps"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>Hello Radixweb</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Considering App component, we are using an img
element.
But what’s fascinating is that we are importing a file from our src folder as if it was an exported variable from that file.
// src/App.js
import "./App.css";
import logo from "./logo.svg";
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>Hello Radixweb</h1>
</header>
</div>
);
}
export default App;
With the syntax: /filename.extension
, any file from the public folder can be used in .js or .css files.
The prime advantage of Create React App is that we can display this svg without ever using an img
element.
This svg can be imported as a component using the syntax:
// src/App.js
import { ReactComponent as Logo } from "./logo.svg";
import "./App.css";
function App() {
return (
<div className="App">
<header className="App-header">
<Logo style={{ height: 300 }} />
<h1>Hello Radixweb</h1>
</header>
</div>
);
}
export default App;
Wondering what’s going on here?
The svg file may be imported as a React Component, which we can then rename using the as
keyword.
To put it another way, we can use our imported svg similarly to a standard component.
It has been difficult to use SVG files in React traditionally. With the help of this component syntax, we can do things like use inline styles. And you can see above that, we set the logo's height to 300px.
To install dependencies, we need to fetch the data from the JSON Placeholder API and display it in our application.
However, dependency is used to create a request to get our posts. And here, we are using a dependency named axios
.
Execute the below command to install axios:
npm install axios
The installed axios will be directly added to the folder node_modules
.
Note: Instead of npm install
, the shorthand command npm i axios
allows you to install more packages.
All of the installed dependencies are immediately accessible from our package .json file and see that the "dependencies" section now includes axios:
{
"name": "my-first-react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.2",
"web-vitals": "^1.0.1"
}
}
In fact, we won't be using it in this project. But the process of using TypeScript with an existing Create React App project is very easy and simple.
To build and test React project, you simply need to install the typescript
dependency and the relevant type definitions:
npm install typescript @types/node @types/react @types/react-dom @types/jest
After this process, it’s time to restart the development server and rename React file that has .js and .tsx extensions.
The good news is now we have a working React and TypeScript project.
Supercharge Your React Development with Radixweb
Get Free Consultation
Let's develop a separate component to get our data and show it rather than writing all of our code inside the App component.
We're going to call this component Posts, so let's make a folder called src to house all of our components and drop the Posts.js file inside of it.
Our component file's full path is src/components/Posts.js
.
We'll use JSON Placeholder to fetch our posts, save them in a state variable named posts, and then map over them to show their title and body:
// src/components/Posts.js
import React from "react";
import axios from "axios";
function Posts() {
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
axios
.get("http://jsonplaceholder.typicode.com/posts")
.then((response) => setPosts(response.data));
}, []);
return (
<ul className="posts">
{posts.map((post) => (
<li className="post" key={post.id}>
<h4>{post.title}</h4>
<p>{post.body}</p>
</li>
))}
</ul>
);
}
export default Posts;
Our post data is being fetched and returned from the Posts component, but in order to display it in our app, we must import it into the App component.
Let's return to App.js and import it by accessing the Posts component from Posts.js in the components folder.
Then, we can add the Posts component under our header
:
// src/App.js
import Posts from "./components/Posts";
import "./App.css";
function App() {
return (
<div className="App">
<header className="App-header">
<img src="/logo.svg" className="App-logo" alt="logo" />
<h1>Hello Radixweb</h1>
</header>
<Posts />
</div>
);
}
export default App;
Once we execute the command, we can see the fetched posts below the header.
Well, this helps to improve the styles of an app.
Create React App extends its support for CSS out of the box. Let’s go back to App.js. As we can see there, we are importing an App.css file from src.
We can modify the app style for a better look and feel within App.css.
Note: Although you can import.css files into any component, our app will use these styles universally. They do not only apply to the component that the imported.css file is placed in.
/* src/App.css */
.App {
text-align: center;
margin: 0 auto;
max-width: 1000px;
}
.App-logo {
height: 50vmin;
pointer-events: none;
}
.App-header {
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(20px + 2vmin);
}
li {
list-style-type: none;
}
.post {
margin-bottom: 4em;
}
.post h4 {
font-size: 2rem;
}
Additionally, a global stylesheet called index.css contains additional style guidelines.
For the body element, we can add a few extra values to make the backdrop black and the text white:
/* src/index.css */
body {
background-color: #282c34;
color: white;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Courier New", "Roboto", "Oxygen","Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
After executing the code, we will have a better appearance of the React application.
Be aware that it is also quite simple to add more advanced CSS configurations to the React project, such as adding CSS modules or SASS.
The README.md file contains some useful resources for CSS style.
Well, we are just a few processes ahead to deploy a React app.
Now we need to run the following command to build the app:
npm run build
This command will create a production build that is optimized for our React project, and it will output the files it has generated along with their sizes:
Compiled successfully.
File sizes after gzip:
46.62 KB build/static/js/2.1500c654.chunk.js
1.59 KB build/static/js/3.8022f77f.chunk.js
1.17 KB build/static/js/runtime-main.86c7b7c2.js
649 B build/static/js/main.ef6580eb.chunk.js
430 B build/static/css/main.5ae9c609.chunk.css
We will see the final output coming from the build tool Webpack. It gives us an idea to understand the size of our app files because the size of our .js files can significantly impact our app's performance.
Every build will modify the unique string or hash that each chunk contains to prevent the browser from saving or caching any fresh deployments.
We probably wouldn't be able to notice any modifications we made to our app if we didn't have this cache-busting hash for each of our files.
Finally, with the help of the npm package serve
, we can start our locally created React project.
This helps us find any errors in the project's final version before publishing it live on the web.
We can use npx to run serve
without installing it globally on our computer, similar to create-react-app.
npx serve
With the help of a server, we can start our app on a different development port than 3000.
Woah! In just 10 steps, we were able to create React app and deploy it successfully.
We can deploy React app on various deployment services like Azure, AWS, GitHub Pages, Netlify, or Firebase.
Finding Difficulty While Developing an Application with React?
Say Hello to Us
As per the official React website, other recommended toolchains are available that allow us to create React projects.
Let’s understand these solutions:
See React in ActionDid you notice something interesting in this tutorial guide?You have just created your first React Project using React developer tools without getting much into the technical details.Isn’t it the beauty of Create React App?It’s not necessary to know everything to create a React app. It gives us the freedom to avoid the complex steps involved in writing React code.Now you know how to start, test, and build a Create project. Consider these commands and understand their usage, as you will need them for your project development.We hope this article turned out to be beneficial!Happy coding!
Ready to brush up on something new? We've got more to read right this way.