Introduction
React is a powerful JavaScript library for building user interfaces, particularly single-page applications where performance and user experience matter. In this tutorial, we will walk you through creating a basic React application that displays a list of users and allows you to add a new one.
Prerequisites
- Basic knowledge of HTML, CSS, and JavaScript.
- Node.js and npm are installed on your machine.
Step 1. Setting Up the React App. We will use Create React App to bootstrap our application.
npx create-react-app react-sample-app
cd react-sample-app
npm start
This will create a new folder, react-sample-app, with the basic setup and start the development server.
Step 2. Creating the User Component. Create a new file called UserList.js inside the src folder.
// src/UserList.js
import React, { useState } from 'react';
function UserList() {
const [users, setUsers] = useState(['Prabhu', 'Balu', 'Saiesh']);
const [newUser, setNewUser] = useState('');
const addUser = () => {
if (newUser.trim() !== '') {
setUsers([...users, newUser]);
setNewUser('');
}
};
return (
<div>
<h2>User List</h2>
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
<input
type="text"
value={newUser}
onChange={(e) => setNewUser(e.target.value)}
placeholder="Add new user"
/>
<button onClick={addUser}>Add User</button>
</div>
);
}
export default UserList;
Step 3. Using the Component in App.js. Open src/App.js and modify it to use the UserList component.
// src/App.js
import React from 'react';
import './App.css';
import UserList from './UserList';
function App() {
return (
<div className="App">
<h1>React Sample Application</h1>
<UserList />
</div>
);
}
export default App;
Step 4. Styling (Optional) Add some basic CSS to App.css to make the app look cleaner.
/* src/App.css */
.App {
font-family: Arial, sans-serif;
padding: 20px;
text-align: center;
}
input {
margin: 10px;
padding: 5px;
}
button {
padding: 5px 10px;
}
Output
When you run the application, you should see.
- A heading that reads “React Sample Application.”
- A list of users: Prabhu, Balu, Saiesh.
- An input box and a button to add a new user.
- The new user appears in the list once added.
Congratulations! Now you’ve created a simple React application that manages a list of users. This foundational knowledge will help you as you build more complex applications with React. Continue exploring additional features, such as props, state management, and hooks, to deepen your understanding.
Happy Learning! Please feel free to comment with your questions, and let us know if this comment was helpful.