I have this set of buttons from A to Z when I click on the particular alphabet the brands related to that letter will pop up. I have tried the below code but it is applying for all the buttons when I click only one button. How do I solve it
let brandList = 'ABCEDEFGHIJKLMNOPQRSTUVWXYZ'.split("");
constructor(props) {
super(props)
this.state = {
bgColor: ""
}
}
getBrandSortData(){
return(
<div className="BrandPageList_AlphabetContainer">
<button value="all" className="BrandPageList_AllButton" onClick={this.handleClick}>All</button>
{brandList.map((item,index) =>
{
let disbaled = !this.isBrandCharacterAvailable(item)
return(
<button
disabled= {disbaled}
value={item}
key={index}
block="BrandPageList_AlphabetButtons"
mods = {{enabled : !disbaled}}
onClick={this.handleClick}
style={{backgroundColor: this.state.bgColor}}
>
{item}
</button>
)}
)}
</div>
)
}
handleClick = event =>{
const brandValues = event.target.value
if(brandValues === "all"){
console.log()
return this.setAllBrands()
}
else{
let brandSortDataByCharacter = this.state.brandSortData[brandValues]
this.setState({
allBrands:
{
[brandValues]: brandSortDataByCharacter
},
bgColor: "red"
})
}
}
Instead of using the event
object to determine what letter you clicked on, you can pass the letter to the click handler when you render it.
Here's an example of how you can achieve this. I'm using a functional component with hooks, since this is the recommended way, but you can do the same in a class component:
const Alphabet = () => {
const [active, setActive] = useState();
return (
<div className='alphabet'>
{'ABCEDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(char => (
<div
className={`letter ${char === active ? 'active' : ''}`}
onClick={() => setActive(char)}>{char}</div>
))}
</div>
);
};
And here's a live example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.