eibersji
eibersji

Reputation: 1216

ReactJS: Uncheck previously checked checkbox when another checkbox is checked

So, I have this code located in Advanced.js. It generates checkboxes.

<div>
    <h6>Sellers</h6>
    {
    data.data.map((item, i) => {
        return <div className="custom-control custom-checkbox" key={i}>
                 <input type="checkbox" className="custom-control-input" id={item.slug} name={item.slug} onClick={this.props.filterItems()}/>
                 <label className="custom-control-label" htmlFor={item.slug}>{item.name}</label>
                </div>
    }) 
    }
</div>

and this is from the index.js. I called Advanced.js: <Advanced filterItems={() => this.getBrand}

and this is the getBrand function:

getBrand = (e) => {
        var checked = !e ? false : e.target.checked
        var name = !e ? "" : e.target.name
        if(checked){
            this.setState({
                brands: name
            }, () => {
                this.filterSeller()
            })
        }else{
            this.setState({
                brands: ""
            }, () => {


    this.home()
        })
    }

}

what happens is that, when I check a checkbox and checked another, both of them are checked. like this:

enter image description here

What I want to happen is that, when I check another checkbox, the previously checked checkbox should become unchecked. How can I do that? Thanks!

Upvotes: 0

Views: 1151

Answers (1)

Jimi Pajala
Jimi Pajala

Reputation: 2368

You should use radio-buttons which are made exactly for this use case https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Upvotes: 2

Related Questions