Debug School

rakesh kumar
rakesh kumar

Posted on

How to submit all data using muliple and single checkbox in react js

select single and multiple checkboxes, and submit the form data to a Node.js server.

Step 1: Set up a new React.js project with the required dependencies.

Create a new project folder and navigate to it in your terminal. Then, run the following command to create a new React.js project:

npx create-react-app checkbox-form
Navigate to the project folder:


cd checkbox-form
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the CheckboxForm component.

In the src folder, create a new file called CheckboxForm.js and add the following code:

import React, { useState, useEffect } from 'react';

const CheckboxForm = () => {
  const [checkboxes, setCheckboxes] = useState([]);
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from the server
    fetch('/data')
      .then((response) => response.json())
      .then((data) => {
        setData(data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }, []);

  const handleCheckboxChange = (event) => {
    const { value, checked } = event.target;

    if (checked) {
      setCheckboxes([...checkboxes, value]);
    } else {
      setCheckboxes(checkboxes.filter((checkbox) => checkbox !== value));
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    // Send checkboxes data to the server
    fetch('/submit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(checkboxes),
    })
      .then((response) => response.json())
      .then((data) => {
        // Handle response from the server
        console.log(data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

  return (
    <form onSubmit={handleSubmit}>
      {data.map((item) => (
        <div key={item.id}>
          <label>
            <input
              type="checkbox"
              value={item.id}
              onChange={handleCheckboxChange}
            />
            {item.name}
          </label>
        </div>
      ))}
      <button type="submit">Submit</button>
    </form>
  );
};

export default CheckboxForm;
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the App component.

Replace the contents of src/App.js with the following code:

import React from 'react';
import CheckboxForm from './CheckboxForm';

const App = () => {
  return (
    <div className="App">
      <h1>Checkbox Form Example</h1>
      <CheckboxForm />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 4: Set up a basic Node.js server.

In the project root directory, create a new file called server.js and add the following code:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

// Mock data from the database
const data = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' },
];

app.get('/data', (req, res) => {
  res.send(data);
});

app.post('/submit', (req, res) => {
  const checkboxes = req.body;
  console.log(checkboxes); // Process the received data

  res.send({ message: 'Data received successfully' });
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Start the React.js development server and the Node.js server.

Open two terminals. In the first terminal, navigate to the project directory and start the React.js development server:

npm start
Enter fullscreen mode Exit fullscreen mode

In the second terminal, navigate to the project directory and start the Node.js server:

Step 6: Verify the application.

Open a web browser and visit http://localhost:3000 to see the Checkbox Form. The form will dynamically display the data fetched from the server, and you can select single or multiple checkboxes. Upon submitting the form, the selected checkboxes will be sent to the Node.js server for further processing.

Top comments (0)