Manage the selection of multiple items when clicking on and off a button or component

I am currently working on implementing a feature with multi-select buttons using a custom component. My goal is to require that at least one option is selected at all times. This means that users can select multiple options, but the last remaining option cannot be deselected without showing an error message indicating that at least one selection is required.

For example, if multiple options are selected, there should be no error displayed:

https://i.sstatic.net/vQ3YV.png

However, if there is only one option selected and the user tries to deselect it, an error message should be shown like this:

https://i.sstatic.net/UjTJB.png

In such cases, a message should appear below stating,

"Atleast one should be selected.."

https://codesandbox.io/s/pedantic-haze-7f214

This sandbox link showcases my current progress towards achieving this functionality. I am also utilizing ReduxForm and building a custom field component with custom validation.

Answer №1

Code for Component

import React, { useState } from "react";
import "./styles.css";
import { Avatar } from "antd";
const daysOfTheWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

export default function App() {
  const [selectedDays, setSelectedDays] = useState({});
  const [error, setError] = useState();
  
  const handleSelect = (day) => {
    if(error) {
      setError(null);
    }
    
    const newSelectedDays = { ...selectedDays, [day]: !selectedDays[day] };
    if(!Object.values(newSelectedDays).find(x => x)) {
      setError('At least one day should be selected..')
      return;
    }
    
    setSelectedDays(newSelectedDays);
  };
  
  return (
    <div className="App">
      {daysOfTheWeek.map((day) => (
        <Avatar
          onClick={() => handleSelect(day)}
          className={`week-day ${selectedDays[day] ? "selected-day" : ""}`}
          key={day}
        >
          {day}
        </Avatar>
      ))}
      {error}
    </div>
  );
}

CSS Styles

.App {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  text-align: center;
}
.week-day {
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 50%;
  padding: 1rem 1.1rem;
  width: 1rem;
  margin: 0.2rem;
  margin-top: 3rem;
  color: black;
}

.selected-day {
  background: magenta;
  color: white;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

Display a unique popover component in React when clicking on the menu

Looking at the menu below: https://i.sstatic.net/ZIwEy.png To open another box by clicking on the three dots, I decided to use a popover from (https://material-ui.com/components/popover/).. However, nothing happens when clicking the dots. It seems that t ...

Alert: Jade has detected an unforeseen block called "scripts"

I created a jade file with the following content: extends layout block content h1= title p Hello and welcome to #{title} block scripts script(src='/socket.io/socket.io.js') script(src='/javascripts/client.js') But when I try ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

Incorporating a static image file into a Material UI cardMedia component within a Next.js project

I am struggling to insert a static image into Material UI CardMedia component. I have tried the following code: const useStyles = makeStyles((theme) => ({ media: { height: 0, paddingTop: "56.25%", // 16:9 }, })); <CardMed ...

Navigation bar with dropdown functionality that adjusts its width based on the content inside

Need help with a CSS dropdown menu issue on my WordPress site. The contents of the submenus are too wide, even after setting a static width for them. I'm looking for a way to make the submenu width adjust dynamically based on the title length. Any exp ...

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

Calculate the total number of randomly generated integers using jQuery

Below are examples of the inputs I have generated: <input type="text" id="rfq_ironilbundle_quotes_offer_price_0" name="rfq_ironilbundle_quotes[offer_price][0]" required="required" class="form-control offered-price"> <input type="text" id="rfq_iro ...

The issue at hand is that the Mongo Atlas model is in place, but for some reason,

https://i.sstatic.net/4m2KT.pngI recently delved into using Next.js and I am a newcomer to backend technologies. I have successfully established a connection with MongoDB Atlas using Mongoose, however, the user object data from the post request is not be ...

Confirm that the CSS syntax is valid

Is there a way to validate CSS syntax by checking for specific characters like "{", "}", ";", and ":"? I have come up with four checks to ensure the code is valid, such as verifying that the number of opening and closing curly braces match, as well as the ...

Enhancing the Appearance of MUI Date Calendar

I'm in the process of creating a calendar similar to mui's <DateCalendar />, and I want to customize the header from 'S M T W T F S' to 'Sun Mon...' as well as adjust the position of the arrows. Before: https://i.sstat ...

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Creating a jQuery AJAX data object that contains numerous values for a single key

My goal is to make an ajax call with multiple values in the same key within the data object. var data = { foo: "bar", foo: "baz" } $.ajax({ url: http://example.com/APIlocation, data: data, success: function (results) { console.log(res ...

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

Utilize Material UI Slider to show only the minimum and maximum markLabels on display

I recently started using Material Ui and I'm having trouble figuring out how to show only the lowest and highest markLabel in a Material UI slider component. range slider For this specific example, I want to display "1888" and "2019" only. Apprecia ...

Perform a jQuery computation using a CSS style

Having trouble with a calculation using a CSS property that is not returning any value. Seems like the issue might be due to the CSS property returning '200px' instead of just '200'. Any suggestions for a workaround? Thanks in advance. ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Creating custom components to encapsulate material-ui functionality

Struggling with the Table component from material-ui? I've divided the table logic into a header and body component, with each row being represented by a different component within the body. export const PRODUCTS = [ {category: 'Sporting Goods ...

Error message for Joi when validating a nested array of objects

I have received user input from the client side and am performing backend validation using Joi. const Joi = require("joi") const schema = Joi.array().items( Joi.object().required().keys({ name: 'filter_list', value: Joi.array(). ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...