user15765833
user15765833

Reputation:

How to change the button colour when it is clicked

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"
        })
    }
}

This is the imageenter image description hereThanks in advance

Upvotes: 2

Views: 75

Answers (1)

Yoav Kadosh
Yoav Kadosh

Reputation: 5175

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

Upvotes: 1

Related Questions