✅ Goal
Create a form in React with multiple checkboxes and submit the selected values to an API endpoint.
🧰 Step 1: Project Setup
If you haven’t already:
bash
npx create-react-app checkbox-array-form
cd checkbox-array-form
npm install axios
npm start
📦 Step 2: Create CheckboxArrayForm Component
Create a new file:
src/CheckboxArrayForm.js
Paste this code:
jsx
import React, { useState } from 'react';
import axios from 'axios';
const CheckboxArrayForm = () => {
const [checkedItems, setCheckedItems] = useState({});
const checkboxes = [
{ name: 'checkbox1', label: 'Checkbox 1' },
{ name: 'checkbox2', label: 'Checkbox 2' },
{ name: 'checkbox3', label: 'Checkbox 3' },
// Add more as needed
];
const handleChange = (event) => {
const { name, checked } = event.target;
setCheckedItems((prev) => ({
...prev,
[name]: checked,
}));
};
const handleSubmit = async (event) => {
event.preventDefault();
// Extract only checked items as an array
const selected = Object.keys(checkedItems).filter((key) => checkedItems[key]);
try {
const response = await axios.post('https://your-api-endpoint.com/submit', {
selectedItems: selected,
});
console.log('API Response:', response.data);
} catch (error) {
console.error('Submission error:', error);
}
};
return (
<form onSubmit={handleSubmit}>
{checkboxes.map(({ name, label }) => (
<label key={name} style={{ display: 'block', marginBottom: '8px' }}>
<input
type="checkbox"
name={name}
checked={checkedItems[name] || false}
onChange={handleChange}
/>
{label}
</label>
))}
<button type="submit">Submit</button>
</form>
);
};
export default CheckboxArrayForm;
🧩 Step 3: Use It in App.js
Update src/App.js
:
jsx
import React from 'react';
import CheckboxArrayForm from './CheckboxArrayForm';
function App() {
return (
<div className="App">
<h1>Checkbox Array Form</h1>
<CheckboxArrayForm />
</div>
);
}
export default App;
📤 Step 4: Send Selected Checkboxes to API
When the form is submitted:
- Only checked items are extracted
- They’re sent as an array to the API using
axios.post
- Replace the URL
https://your-api-endpoint.com/submit
with your real API
Example payload sent:
json
{
"selectedItems": ["checkbox1", "checkbox3"]
}
💡 Extras You Can Add
- ✅ Validation (e.g., at least one checkbox must be selected)
- 🎨 Styling with Tailwind or styled-components
- 💾 Show confirmation messages or loading spinners
- 🧪 Unit tests with Jest + React Testing Library