Ali
Ali

Reputation: 13

How to make my checkbox to be clicked only once and other are unchecked in React.js

I followed a tutorial and created a form with as many checkboxes to be clicked. But, in another case, I need only one box to be checked. The values of checkboxes are dynamic and you never know, how many checkboxes will be created. But, only one can be clicked. Can you please help me in finding the solution thankyou.

import React, { Component } from 'react';
import Checkbox from "./Checkbox.component";

class PatientSelectTiming extends Component {
state = { 
      options: [...this.props.props],
      checkboxes: [...this.props.props].reduce(
        (options, option) => ({
          ...options,
          [option]: false
        }),
        {}
      ),
      appointmentSlots: null
  };

  handleCheckboxChange = e => {
    const { name } = e.target;
    

    this.setState(prevState => ({
      checkboxes: {
        ...prevState.checkboxes,
        [name]: !prevState.checkboxes[name]
      }
    }))
    }

  handleFormSubmit = formSubmitEvent => {
    formSubmitEvent.preventDefault();
    Object.keys(this.state.checkboxes)
      .filter(checkbox => this.state.checkboxes[checkbox])
      .forEach(checkbox => { 
        let appointmentSlot = [];  
        appointmentSlot.push(checkbox); 
        console.log(appointmentSlot);
        this.setState({appointmentSlots: appointmentSlot})
        localStorage.setItem('appointmentSlots', JSON.stringify(appointmentSlot))     
    });  
  };

  createCheckbox = option => (
    <Checkbox
      label={option}
      isSelected={this.state.checkboxes[option]}
      onCheckboxChange={this.handleCheckboxChange}
      key={option}
    />
  );

  createCheckboxes = () => this.state.options.map(this.createCheckbox);

  render() {
    return (
      <div>
        <p>Only select one item and only first date clicked will be your time</p>
            <form onSubmit={this.handleFormSubmit}>
              {this.createCheckboxes()}
                <button type="submit">
                  Save
                </button>
            </form>
    {this.state.appointmentSlots === null ? <p>Click on any slot to get your time.</p> : <p>Your time is {JSON.parse(localStorage.getItem("appointmentSlots"))}</p>}
    </div>
          )
    }
  }
export default PatientSelectTiming;

Upvotes: -1

Views: 499

Answers (1)

destroyer22719
destroyer22719

Reputation: 404

You can use a radio button https://www.w3schools.com/tags/att_input_type_radio.asp Radio button is the same as checkbox but only allows users to check only 1 option.

Upvotes: 1

Related Questions