简体   繁体   中英

How to change background color of button using react

I am working on react using bootstrap, initially I am giving same colors to my buttons, now What I am trying to do is on click of button change that button's color and if I click on other button it change the color of that and the first one back to basic (default) color

I have done this using jquery earlier as passing onclick event and toggle the color but here I am new to react so don't know how to do that.

My code

code sandbox

What I am looking for is suppose I have 7 buttons and I click on first one then its color should change, then If I am clicking on next button then first should come to normal and the clicked (second) one should changed the color.

Important the first button should always be in active mode ie it should have the active color then if next clicked that color changes to normal and the clicked one should take the color

import React from 'react'

function Stddata() {
    const button_Data = [
      {
        "name": "Name",
        "value": "name"
      },
      {
        "name": "Class",
        "value": "class"
      },
      {
        "name": "Age",
        "value": "age"
      },
      {
        "name": "Subjects",
        "value": "subjects"
      },
      {
        "name": "School",
        "value": "school"
      }
    ]
    return (
        <div>
            { button_Data.map(item => (
                <div key={item.value}>
            <button 
                className="btn btn-outline-secondary mb-1 form-control text-left"
                value={item.value}
                onClick={props.trigerOnClickEmpSideBtn}
            >{item.name}</button>
            </div>
            ))}   
        </div>
    )
}

export default Stddata

You'll need to use some state. In your component, let's define which button is currently active. We can use useState and set its starting value to 0, as you said you want to the first button to start out as active:

import React, { useState } from 'react'

// inside your component
  const [activeButton, setActiveButton] = useState(0)

And your button's onClick will reference the function to change the currently active button. Within the className , it will check if its own index is the same as the currently active button, and set the css class accordingly:

{button_Data.map((item, index) => (
  <button 
    className={`btn ${activeButton === index ? 'btn-success' : null}`}  
    value={item.value} 
    onClick={ () => {setActiveButton(index)} }
  >

    {item.name}

  </button>
))}

Edit: Adding Working Demo

I actually had to break off each button into its own component because each button now needs to manage its own state. The underlying principle is the same, but each button is now its own component with its own state.

Edit 2:

With the changes to the initial quesiton, I changed the answer. The codesandbox also reflects these changes. The codesandbox still uses a separate component for the button, though that's not really necessary based on the new question parameters - but the principle is the same.

What you need to do is to store an active state for the button, default the state to the name of the first button.

Once you do that you can set an active className for the button which is selected.

onClick event of the button update the activeButton state.

const button_Data = [
  {
    name: "Name",
    value: "name"
  },
  {
    name: "Class",
    value: "class"
  },
  {
    name: "Age",
    value: "age"
  },
  {
    name: "Subjects",
    value: "subjects"
  },
  {
    name: "School",
    value: "school"
  }
];
function Stddata(props) {
  const [activeButton, setActiveButton] = useState(button_Data[0].name);
  const handleClick = e => {
    const name = e.target.name;
    setActiveButton(name);
  };
  return (
    <div>
      {button_Data.map(item => {
        const className = activeButton === item.name ? "active" : "";
        return (
          <div key={item.value}>
            <button
              className={`btn btn-outline-secondary mb-1 form-control text-left ${className}`}
              name={item.name}
              value={item.value}
              onClick={handleClick}
            >
              {item.name}
            </button>
          </div>
        );
      })}
    </div>
  );
}

export default Stddata;

Working demo

use this component for buttons

    import React from 'react';
    import {View,StyleSheet, TouchableOpacity} from 'react-native'

const Btn= props =>{
    if(props.touch){
        return (
        <TouchableOpacity style={{...styles.boxes, ...props.style}} onPress={props.onPress}>
            {props.children}
        </TouchableOpacity>
        );
    }else{
        return (
            <View style={{...styles.boxes, ...props.style}}>
                {props.children}
            </View>
        );
    }

}
const styles= StyleSheet.create({
    boxes :{
        padding:18,
        backgroundColor:'white',
        borderRadius:20        
    }
});

export default Btn;

and in the page u want to have Btn use it like this

<Btn style={styles.items} touch="on" onPress={props.getProductsRequest}>
               <Text  style={styles.itemTxt}> some thex</Text>
        </Btn>

pay attention to the touch = on

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM