score:2
Accepted answer
Here is something I made very quickly just to show a working example (can be much better and shorter but I thought this will help make it more understandable). If you need any extra help, will be happy to update my answer ;)
import { useState } from "react";
import "./styles.css";
const initialCheckBoxesState = [
{ name: "one", checked: false },
{ name: "two", checked: false },
{ name: "three", checked: false },
{ name: "four", checked: false },
{ name: "five", checked: false }
];
export default function App() {
const [checkBoxes, setCheckedBoxes] = useState(initialCheckBoxesState);
const [error, setError] = useState("");
const handleCheckOnClick = (event) => {
setError("");
let checkBoxIndex = checkBoxes.findIndex(
(box) => box.name === event.target.name
);
let copyOfCheckBoxes = [...checkBoxes];
let isChecked = copyOfCheckBoxes[checkBoxIndex].checked;
let amountOfCheckedBoxes = checkBoxes.filter((box) => box.checked);
if (!isChecked && amountOfCheckedBoxes.length > 2) {
setError("Max of 3 checked checkboxes");
return;
}
if (isChecked) {
copyOfCheckBoxes[checkBoxIndex] = {
...copyOfCheckBoxes[checkBoxIndex],
checked: false
};
} else {
copyOfCheckBoxes[checkBoxIndex] = {
...copyOfCheckBoxes[checkBoxIndex],
checked: true
};
}
setCheckedBoxes(copyOfCheckBoxes);
};
return (
<div className="App">
{checkBoxes.map((box, index) => {
return (
<input
key={index}
type="checkbox"
name={box.name}
onChange={handleCheckOnClick}
checked={box.checked}
/>
);
})}
<span>{error}</span>
</div>
);
}
Source: stackoverflow.com
Related Query
- How can I restrict user from not to select more than three checkbox in reactjs
- How can i restrict user from not selecting other file types using input type file with react and typescript?
- how to restrict user from entering more than 10 numbers in react
- Yup validation to accept more than 0 input digit. Like user can enter 0.001 or 0.0001. But not only 0
- How can I get more than one value from the Redux store in a single statement?
- How can I get more than one document from mongoDB?
- On an editable material-table, how can you restrict the user to not be able to enter chars, special characters or negative numbers?
- React/Material-UI: How can I map multiple tables from a JSON object with more than one array of data?
- How can I display more than one component from the same file in the App.js?
- How can i import more than one component from the same folder?
- How can i access the main component from not its child? reactjs
- if I have more than three cards, how can i create a new row for the 4th card in reactstrap or bootstrap?
- how to restrict text typing and extra text adding but not italic bold highlighting so that user cannot add text but that can bold text
- How can i pass different props to more than one children component from the parent one in React?
- how can i get the more than one data row value based on selected checkbox and store in useState (react-table-boostrap2)
- How can i extract more than one key from an Object and print the output
- ReactJS - How can I set a value for textfield from material-ui?
- How can I call methods on Reactjs components in the browser console or from an outside script?
- How can I get the URL address from the browser in ReactJS (servers URL)
- How can I tell whether ReactJS is in development mode from JavaScript?
- How to get User information from JWT cookie in NextJS / ReactJS
- How can I show a different sidebar based on user information? After logged in. ReactJS
- ReactJS when using HTML attribute checked, reactjs is not allowing to select the checkbox
- How can I style a Select from Material UI with styled components?
- Reactjs onClick event how to select a specific button from a list
- How can i get array of object from this data for state and count in reactjs
- I can not get the state from react router Link component using useLocation. So how can I pass it?
- How to populate select dropdown elements with data from API - ReactJS
- How can I get the name of the current user from the Json Web Token?
- React Material-UI How can I add a checkbox which is separate from table row click
More Query from same tag
- How to instantiate class which is returned from a function?
- how do i filter json get data
- Is there a way to populate option html tag with an array in react?
- How to throw an error in this.state.forEach statement in react
- Firebase and ReactJS - Authentication Using Local Storage
- template getter must return HTMLTemplateElement in polmer <google-map> component
- Meteor / React - return Meteor callback in render
- MUI v5 - Extending Typography variant in TypeScript creates error "No overload matches this call"
- How to find an element by id in nested arrays
- TS keyof typeof <Object> does not allow object.keys(<Object>) to be assigned?
- JavaScript React JSX: Looping Through Array of Objects And Setting Objects Horizontally Across Web Page
- Search Function unresponsive in React
- How to get id from clicked doc firebase react?
- plugin/preset files are not allowed to export objects only functions
- TypeError: Cannot read property 'history' of undefined in Jquery - React
- React Js input is losing focus when I try typing in it but only when onChange is added
- React components make inheritance through Compositon
- How to display the content of an array inside an object in Reactjs
- OnMouseDown fires more than once in Scatterplot
- Get value from Apollo Store
- axios GET request function export/ import in react
- Firebase Reactjs - ae.collection is not a function
- React Authentication session management
- Clicks on ReactJS components not firing on an OpenLayers Overlay
- show a message to the user using react-alert
- Is it possible to have an upColor on a Area graph using Highcharts?
- useLocation can't be mocked with jest.fn() (while useHistory can be)
- implementing infinite loop of changing text with React Hooks
- Unable to initialize when loading Firebase SDKs from reserved URLs
- Conditionally show filtered posts or normal posts with Javascript in Gatsby project