Introduction
Welcome to the exciting world of React! As one of the most popular JavaScript libraries for building user interfaces, React has revolutionized web development by providing a powerful and efficient way to create interactive and dynamic web applications.
If you're new to React or just starting your journey in web development, you've come to the right place. This comprehensive guide is designed to be your go-to resource for mastering the fundamentals of React and setting you on the path to becoming a proficient React developer.
In this article, we'll walk you through the essential concepts of React, step by step. From setting up your development environment to creating your first React component, handling data covering the basics. Whether you're a seasoned developer looking to revise the basics or an absolute beginner eager to dive into the world of front-end development, we've got you covered.
Before we embark on this journey, you might wonder, "Why should I learn React?" The answer is simple: React's component-based architecture and the concept of a Virtual DOM allow for faster and more efficient rendering, making web applications highly responsive and scalable. Moreover, React's vibrant community and extensive ecosystem of libraries and tools make it a versatile framework that suits projects of all sizes.
Let's get started with React!
Setting up the development environment
Step 1: Install Node.js and npm
Head to the official Node.js website (nodejs.org) and download the latest stable version of Node.js for your operating system.
Run the installer and follow the installation instructions to install Node.js.
Node.js comes with npm (Node Package Manager) bundled, which you'll use to manage your React project's dependencies.
Step 2: Choose a Code Editor
Choose a code editor that suits your preferences. Some popular choices are Visual Studio Code, Sublime Text, Atom, or WebStorm.
Install your preferred code editor on your system.
Step 3: Create a New React Project
- Open your terminal or command prompt.
Use create-react-app
to generate a new React project. It's an officially supported tool that sets up a React environment with all the necessary configurations and dependencies.
npx create-react-app my-react-app
Step 4: Navigate to the Project Directory
Change the working directory to your newly created project:
cd my-react-app
Step 5: Start the Development Server
- Now, let's start the development server. This will allow you to see your React app in action and make changes in real time.
npm start
After running the above command, your React app will be available at localhost:3000. You can access it using your web browser.
Step 6: Explore Your React Project Structure
With the development server running, your React app will automatically open in your default web browser.
Open your code editor and navigate to the project folder. You'll find the following directories and files:
The
src
directory contains the main source files of your React application.The
public
directory contains public files likeindex.html
, which is the entry point of your app.
Now your development environment is all set so let's move on...
Components
The code of the application resides in the src folder. Let's simplify the default code such that the contents of the file index.js looks like this:
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
and file App.js looks like this
const App = () => (
<div>
<p>Hello world</p>
</div>
)
export default App
The files App.css, App.test.js, index.css, logo.svg, setupTests.js and reportWebVitals.js may be deleted as they are not needed in our application right now.
The file App.js now defines a React component with the name App. The command on the final line of file index.js
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
renders its contents into the div-element, defined in the file public/index.html, having the id value 'root'.
By default, the file public/index.html doesn't contain any HTML markup that is visible to us in the browser:
<!DOCTYPE html>
<html lang="en">
<head>
content not shown ...
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
You can try adding there some HTML to the file. However, when using React, all content that needs to be rendered is usually defined as React components.
Let's take a closer look at the code defining the component:
const App = () => (
<div>
<p>Hello world</p>
</div>
)
As you probably guessed, the component will be rendered as a div-tag, which wraps a p-tag containing the text Hello World.
Technically the component is defined as a JavaScript function. The following is a function (which does not receive any parameters):
() => (
<div>
<p>Hello world</p>
</div>
)
The function is then assigned to a constant variable App:
const App = ...
There are a few ways to define functions in JavaScript. Here we will use arrow functions.
Because the function consists of only a single expression we have used a shorthand, which represents this piece of code:
const App = () => {
return (
<div>
<p>Hello world</p>
</div>
)
}
In other words, the function returns the value of the expression.
The function defining the component may contain any kind of JavaScript code. Modify your component to be as follows:
const App = () => {
console.log('Hello from component')
return (
<div>
<p>Hello world</p>
</div>
)
}
export default App
and observe what happens in the browser console, you can open the console in your browser using
Google Chrome and Microsoft Edge:
Windows/Linux: Press
Ctrl + Shift + J
Mac: Press
Cmd + Option + J
Mozilla Firefox:
Windows/Linux: Press
Ctrl + Shift + K
Mac: Press
Cmd + Option + K
Safari:
- Mac: Press
Cmd + Option + C
The first rule of frontend web development:
keep the console open all the time
Note that you should not remove the line at the bottom of the component
export default App
Without the export, the component and the whole app break down.
JSX
It seems like React components are returning HTML markup. However, this is not the case. The layout of React components is mostly written using JSX. Although JSX looks like HTML, we are dealing with a way to write JavaScript. Under the hood, JSX returned by React components is compiled into JavaScript.
After compiling, our application looks like this:
const App = () => {
const name = 'John Doe';
const age = 30;
return (
<div>
<h1>Welcome to My Website</h1>
<p>Hello, {name}!</p>
<p>You are {age} years old.</p>
</div>
)
}
Inside the component, we used JSX to define the content to be displayed:
The
<div>
element is a container that wraps the content we want to render. It's a common practice to have a single root element for each component.The
<h1>
element displays the main heading "Welcome to My Website."We used curly braces
{}
to embed JavaScript expressions inside JSX. In this case, we're using the variablesname
andage
.The
<p>
elements display dynamic text based on the values ofname
andage
.
The compilation is handled by Babel. Projects created with create-react-app are configured to compile automatically.
It is also possible to write React as "pure JavaScript" without using JSX. Although, nobody with a sound mind would do so.
In practice, JSX is much like HTML with the distinction that with JSX you can easily embed dynamic content by writing appropriate JavaScript within curly braces. The idea of JSX is quite similar to many templating languages, such as Thymeleaf used along with Java Spring, which are used on servers.
JSX is "XML-like", which means that every tag needs to be closed. For example, a newline is an empty element, which in HTML can be written as follows:
<br>
but when writing JSX, the tag needs to be closed:
<br />
Multiple components
Let's modify the file App.js as follows (NB: export at the bottom is left out in these examples, now and in the future. It is still needed for the code to work):
const Hello = () => { return ( <div> <p>Hello world</p> </div> )}
const App = () => {
return (
<div>
<h1>Greetings</h1>
<Hello /> </div>
)
}
We have defined a new component Hello and used it inside the component App. Naturally, a component can be used multiple times.
Writing components with React is easy, and by combining components, even a more complex application can be kept fairly maintainable. Indeed, a core philosophy of React is composing applications from many specialized reusable components.
PROPS: passing data to components
It is possible to pass data to components using so-called props.
Let's modify the component Hello as follows:
const Hello = (props) => { return (
<div>
<p>Hello {props.name}</p>
</div>
)
}
Now the function defining the component has a parameter props. As an argument, the parameter receives an object, which has fields corresponding to all the "props" the user of the component defines.
The props are defined as follows:
const App = () => {
return (
<div>
<h1>Greetings</h1>
<Hello name='George' />
<Hello name='Daisy' />
</div>
)
}
There can be an arbitrary number of props and their values can be "hard-coded" strings or the results of JavaScript expressions. If the value of the prop is achieved using JavaScript it must be wrapped with curly braces.
Let's modify the code so that the component Hello uses two props:
const Hello = (props) => {
console.log(props) return (
<div>
<p>
Hello {props.name}, you are {props.age} years old </p>
</div>
)
}
const App = () => {
const name = 'Peter' const age = 10
return (
<div>
<h1>Greetings</h1>
<Hello name='Maya' age={26 + 10} />
<Hello name={name} age={age} />
</div>
)
}
The props sent by the component App are the values of the variables, the result of the evaluation of the sum expression and a regular string.
Component Hello also logs the value of the object props to the console since we used console.log()
Software development is hard. It gets even harder if one is not using all the possible available tools such as the web-console and debug printing with console.log. Professionals use both all the time and there is no single reason why a beginner should not adopt the use of these wonderful helper methods that will make life so much easier.
Now we will learn about the Component state and event handling in the next blog i.e. "React 101: Your Comprehensive Guide to Getting Started with React Part-2"