Over the past decade, front-end development has experienced a massive influx of technologies and tools, and frameworks have played a crucial role in shaping how we build UIs and web applications. One such framework that has gained immense popularity is React. Developed by Meta (formerly known as Facebook) in 2013, React is a widely-used JavaScript library for building highly interactive user interfaces and web applications. With React, you can build rich UIs that engage users. In this tutorial, I will guide you through the process of getting started with React.
Table of Contents:
- What is React?
- Why use React?
- React Basics
- How to install React
- JSX
- Components
- Class components
- Functional components
- Props
- State
- How to build a simple to-do app
What is React?
React is a JavaScript frontend library for building highly interactive UIs. It was developed by Facebook and is open source, meaning anyone can contribute as long as they follow the guidelines.
Why use React?
React is built on the component architecture, which means that UIs are built from smaller components, making it easy to build UIs. Additionally, React has a shorter learning curve compared to other frontend frameworks. Learning React is almost like working with JavaScript itself. React is also popular in the frontend community, so as a developer, learning React can lead to more opportunities. As a recruiter or HR professional, you can be confident that open React positions will be filled quickly, as there is a large pool of developers to pull from. Lastly, the React ecosystem is vast, and there are many people willing to help you on your journey if you get stuck.
React Basics
How to Install React
To start using React, you need to have Node.js installed on your computer system. To install Node, go to www.nodejs.org and follow the prompts. If you're unsure whether your computer has Node installed, type "node -v" in the terminal. If you have Node installed, you will get the version you have installed. Any error message means that you don’t have it installed.
To get started with React, type npx create-react-app <folder name>
in your terminal. After running this command, a React app will be generated for you. When your app has been created, move into the <folder name>
you specified when you ran the first command. After moving into the folder, you need to start your app. To start your app, type npm run start
in the terminal. You should see something like this on your default web browser:
Yay! You have created your first React app. Now, let's look at the building blocks of React.
JSX
If you look at the JavaScript files, you will see function(s) that return something that looks like HTML. That is called JSX—JavaScript Syntax Extension. You can think of it as HTML-flavored JavaScript.
JSX makes it so much easier to build UI components in React. It is a more convenient way to create DOM elements/nodes. It behaves like HTML but has the capabilities of JavaScript. JSX can also evaluate JavaScript expressions. You just have to wrap them inside curly braces {}
. It looks something like this:
Components
Components are the building blocks of UIs in React. There are two types of components in React: class-based components and functional components.
Class-based components were the initial way of creating components in React. They are declared with the class keyword and extend the React component class.
Functional components are a newer and cleaner way of creating React components. Unlike class components, functional components are created as normal JavaScript functions, but with some caveats. Firstly, the function name must start with a capital letter. Secondly, the only parameter it takes is "props" (though it can be destructured). Lastly, it can only return JSX, with a single parent in the case of multiple JSX elements.
Using functional components is much cleaner and easier to read.
Props
Props in React are simply an object that contains all the attributes of a component, just like passing attributes to vanilla HTML elements. However, in React components, the attributes are accessed through the props object, which is read-only and cannot be modified. Props are a way for a parent component to communicate with its child components.
State
State, on the other hand, is any data that can change and be tracked. State is where the data required by a component is stored, and when state changes, the component re-renders. In functional components, you use the useState
hook to create state, which returns an array with exactly two values: state and a function to set the state. The state can be of any data type, but usually, developers use arrays or objects. In simpler cases, strings and numbers can be used.
State can be used to store a wide range of data, such as the theme of the website, the current page of the website, and the current user. State and props are what make React a very powerful library.
Now we have learned the building blocks of React, let’s apply our knowledge by building a simple to-do app.
Components of Our To-do App
Our to-do app will have the following capabilities:
- Creating a task
- Updating a task
- Deleting a task
- Displaying tasks on the screen
Setting Up the Project
To get started, we need to create a new React project. Open your terminal and create a new folder where your project will live. Navigate to the created folder in your terminal and enter the following command to create a new React project:
npx create-react-app my-to-do-app
This command will create a new React app with the name my-to-do-app
.
Once the app is created, navigate into the directory using the following command:
cd my-to-do-app
To start the React development server, enter the following command in your terminal:
npm run start
This command will start a development server for your project. You can now view your app by navigating to http://localhost:3000
in your web browser.
Creating the To-do App
Now that our project is set up, let's create our to-do app. The first step is to clear up the boilerplate code in our App.js file.
In your App.js
file, add the following code snippets:
import React from 'react';
function App() {
return (
<div>
<h2>Create a New Task</h2>
<form>
<label htmlFor="taskName">Task Name:</label>
<input type="text" id="taskName" name="taskName" />
<button type="submit">Add Task</button>
</form>
</div>
);
}
export default App;
This code creates a simple form with an input field and a button. The label
element is used to associate the input
element with the text Task Name:
. The htmlFor
attribute of the label
element is set to the id
of the input
element, so when the user clicks on the text Task Name:
, the corresponding input
element is focused.
Handling User Input
When building a React application, we often need to maintain a state, which is a JavaScript object that stores the data that the component needs to render. In this case, we want to keep track of the tasks that the user adds and display them on the screen.
To create a state in a functional component, we use the useState
hook, which is a built-in React hook. The useState
hook takes an initial value and returns an array with two elements. The first element is the state itself, and the second element is a function that updates the state.
In our case, we want to create two states. The first state will store the text that the user types into the input field, and the second state will store an array of tasks. Here's how we create these states:
const [taskText, setTaskText] = useState("");
const [tasks, setTasks] = useState([]);
Notice that we're using array destructuring to get the state and the updater function for each state. The initial value for taskText
is an empty string, and the initial value for tasks
is an empty array.
Now that we have our states, we need to update them when the user interacts with the UI. To do this, we'll use the onChange
event on the input field to update the taskText
state whenever the user types something:
<input
type="text"
value={taskText}
onChange={(e) => setTaskText(e.target.value)}
/>
Here, we're using the value
prop to bind the input field to the taskText
state, and the onChange
prop to listen for changes to the input field and update the state accordingly.
Next, we'll create a function to add tasks to the tasks
state when the user clicks the "Add Task" button:
const handleAddTask = () => {
setTasks([...tasks, { text: taskText }]);
setTaskText("");
};
Here, we're using the spread operator (...
) to create a new array that includes all the existing tasks as well as a new task object with the text from the taskText
state. We're then updating the tasks
state with the new array, and resetting the taskText
state to an empty string.
Finally, we need to display the tasks on the screen. To do this, we'll use the map
method to loop through the tasks
array and render a list item for each task:
<ul>
{tasks.map((task, index) => (
<li key={index}>
{task.text}
<button onClick={() => handleDeleteTask(index)}>Delete</button>
<button onClick={() => handleEditTask(index)}>Edit</button>
</li>
))}
</ul>
Here, we're using the map
method to create a new array of list items (<li>
elements) for each task in the tasks
array. We're using the key
prop to give each list item a unique identifier (in this case, the index of the task in the array). We're also rendering a "Delete" button and an "Edit" button for each task, which will be handled by their respective event handlers.
Let's continue with creating the delete and edit functions.
To add the final touches to our to-do app, we need to implement the functionality for deleting and editing tasks. Let's start with the delete function.
Here's the code for the delete function:
const deleteTask = (taskToDelete) => {
const updatedTasks = tasks.filter((task) => task !== taskToDelete);
setTasks(updatedTasks);
};
What we did here is create a function called deleteTask
that takes a taskToDelete
parameter. Inside the function, we use the filter
method to create a new array of tasks that doesn't include the task to delete. We then update our tasks
state with this new array.
Now let's move on to the edit function.
Here's the code for the edit function:
const editTask = (taskToEdit, newTask) => {
const updatedTasks = tasks.map((task) => {
if (task === taskToEdit) {
return newTask;
} else {
return task;
}
});
setTasks(updatedTasks);
};
Similar to the delete function, we create a function called editTask
that takes a taskToEdit
parameter and a newTask
parameter. Inside the function, we use the map
method to create a new array of tasks. We loop through each task, and if the task matches the task to edit, we replace it with the new task. Otherwise, we leave it unchanged. We then update our tasks
state with this new array.
With these two functions added, our to-do app is now complete! Here's the final code for our project:
import React, { useState } from "react";
function App() {
const [inputValue, setInputValue] = useState("");
const [tasks, setTasks] = useState([]);
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
const handleAddTask = () => {
if (inputValue.trim() !== "") {
setTasks([...tasks, inputValue]);
setInputValue("");
}
};
const deleteTask = (taskToDelete) => {
const updatedTasks = tasks.filter((task) => task !== taskToDelete);
setTasks(updatedTasks);
};
const editTask = (taskToEdit, newTask) => {
const updatedTasks = tasks.map((task) => {
if (task === taskToEdit) {
return newTask;
} else {
return task;
}
});
setTasks(updatedTasks);
};
return (
<div>
<h2>Create a New Task</h2>
<form>
<label htmlFor="taskName">Task Name:</label>
<input type="text" id="taskName" name="taskName" />
<button type="submit">Add Task</button>
</form>
<ul>
{tasks.map((task) => (
<li key={task}>
{task}
<button onClick={() => deleteTask(task)}>Delete</button>
<button onClick={() => editTask(task, prompt("Enter new task"))}>
Edit
</button>
</li>
))}
</ul>
</div>
);
}
export default App;
Conclusion
In conclusion, you have learned what React is, the history of React, basics of React, and how to create a simple to-do app with React. This is just the beginning of what you can achieve with React. With practice and more knowledge, you can build more complex and sophisticated web applications using React. I hope you found this tutorial helpful. If you have any questions or feedback, feel free to leave a comment. Good luck with your React journey!
Top comments (2)
That is good blog , Thank you for sharing for us
Glad you found it valuable