I have a e-commerce project and filter page. In the filter page I have a few brands with checkbox inputs to filter by brands when checkbox checked. When brands input checked I manipulete the url for saving checked brands in case of page reload like (http://localhost:3000/product-list?categories=2&brands=1,12). My problem is when I checked my brand with id 12, id 1 and id 2 brands also checked.
My checkbox componenet
import React from "react";
import "./CheckBox.style.scss";
import { withRouter } from "react-router-dom";
class CheckBox extends React.Component {
constructor(props) {
super(props);
this.checkboxRef = React.createRef();
}
componentDidUpdate(prevProps) {
if (
this.props.location.search !== prevProps.location.search &&
this.checkCategoryChanges(
this.props.location.search,
prevProps.location.search
) &&
this.checkboxRef.current.checked
) {
this.checkboxRef.current.checked = false;
}
}
checkCategoryChanges(currentUrl, prevUrl) {
let items =
currentUrl.charAt(0) === "?"
? currentUrl.slice(1).split("&")
: currentUrl.split("&");
for (const item of items) {
if (
(item.indexOf("categories") !== -1 && prevUrl.indexOf(item) === -1) ||
(item.indexOf("categories") !== -1 && items.length === 1)
) {
return true;
}
}
return false;
}
isChecked() {
const mainUrlAsArray = window.location.href.split("?");
if (mainUrlAsArray.length === 2) {
const url = mainUrlAsArray[1];
let checkedItems =
url.charAt(0) === "?" ? url.slice(1).split("&") : url.split("&");
for (const item of checkedItems) {
if (
item.indexOf(this.props.urlKey) !== -1 &&
item.split("=")[1].indexOf(this.props.value) !== -1
) {
return true;
}
}
return false;
}
}
runOnChange(e) {
const checkboxData = {
value: this.props.value,
urlKey: this.props.urlKey,
isChecked: e.target.checked,
type: this.props.type ? this.props.type : "checkbox",
};
this.props.onChange(checkboxData);
}
render() {
return (
<label className="checkbox-group">
<input
ref={this.checkboxRef}
defaultChecked={this.isChecked() ? true : undefined}
value={this.props.value}
onClick={(e) => this.runOnChange(e)}
type={this.props.type ? this.props.type : "checkbox"}
className="checkbox"
name={this.props.name}
/>
<span className="checkBoxLabel">{this.props.text}</span>
</label>
);
}
}
export default withRouter(CheckBox);
Aucun commentaire:
Enregistrer un commentaire