Here is some code and detailed steps that you can follow to create a to-do list with Node.js and React:
1. Set up a Node.js server:
- Install Node.js on your system if it is not already installed.
- Create a new directory for your project and navigate to it in the terminal.
- Run npm init to create a package.json file for your project.
- Create a file called "server.js" in the root directory of your project and add the following code to set up a simple server:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
- Install the necessary dependencies by running npm install express cors body-parser. These packages will allow you to set up a simple server and handle HTTP requests and responses.
Now let's setup React framework
- Install the create-react-app tool by running npm install -g create-react-app.
- Use the create-react-app tool to create a new React app in the same directory as your Node.js server by running create-react-app client. This will create a new subdirectory called "client" with a basic React app set up.
Now Create a to-do list component in React:
- In the "client" directory, open the file "src/App.js" and replace the contents with a new functional component called "ToDoList".
import React, { useState } from 'react';
function ToDoList() {
const [items, setItems] = useState([]);
return (
<div>
<form>
<input type="text" />
<button type="submit">Add</button>
</form>
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
export default ToDoList;
- In the "ToDoList" component, create a state variable called "items" to store the to-do list items. Use the "useState" hook to create the state variable and a function to update it.
- Add a form with an input field and a submit button to the component. The form should allow the user to add new items to the list. You can use the "onSubmit" event of the form to handle the submission of the form.
- Display the list of items in the component using a "ul" element. Use the "map" function to render a list item for each item in the "items" state variable.
Finally let's Connect the React frontend to the Node.js backend:
Connect the React frontend to the Node.js backend:
const baseUrl = 'http://localhost:5000';
export const getItems = async () => {
const res = await fetch(`${baseUrl}/
Top comments (0)