Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - select upto 3 in category list from array in list in react.js

I am working in react, fixed-sized array but I am not getting output when I am select up to 3 record but it show only 1 record select.

CODE:

this.state = { 
    type: [3],  //select upto 3 record(type select from category)
    categoryList: null,  //  category-list
};
changeCategory(o){
    this.setState({type: o})
} 
<div>
{ categoryList.map((o,index)=>{
  return <div key={index} className={"rounded " +  (type==o.slug ?"selected" : '')} onClick={()=>this.changeCategory(o.slug)} style={{padding: "2px 5px"}}>{o.name}</div>
  })
}
</div>

category image here

question from:https://stackoverflow.com/questions/65840111/select-upto-3-in-category-list-from-array-in-list-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ISSUE

type is a state array and you are comparing it like the value in the render method. In this way, you always have just one item selected instead of 3 items.

SOLUTION

This code will help you to select 3 items

this.state = { 
    type: [], 
    ....
};

// this will add selected item in `type` array if length not exceed
changeCategory(o){
  if(type.length !== 3){ // for limit of 3
    const newType = [...this.state.type];
    newType.push(o.slug);
    this.setState({type: newType});
  }
}

<div>
  {categoryList.map((o, index) => {
    return (
      <div
        key={index}
        className={
          "rounded " + (this.state.type.includes(o.slug) ? "selected" : "")
        }
        onClick={() => this.changeCategory(o.slug)}
        style={{ padding: "2px 5px" }}
      >
        {o.name}
      </div>
    );
  })}
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...