Home > OS >  toggle between two button style in react js
toggle between two button style in react js

Time:08-31

I want the button's style to change when I click on them. I want the option 1 button to be selected and background color to change to by default. If I click on the option 2 button, I want the option 2 button to change and unchanged option 1. I already used the method found in this post However, the method doesn't seems to be working correctly since the color of my buttons is the default HTML button color.

My code:

import React, {Component} from 'react';
import './OptionButtons.css'

export class OptionButtons extends Component{
    constructor() {
        super();
        this.state = {
            selected: "btn1"
        };
}

changeColor = (btn) => {
    this.setState({ selected: btn });
};

addClass = (btn) => {
    if (this.state.selected === btn) return "selected";
    else return "notSelect";
};


render() {
    return (
        <div class = "option">
            <h2> Options </h2>
            <div class = "buttons">
                <button id = "option1Btn" className = {this.addClass("btn1")} onClick = {this.changeColor.bind(this, "btn1")}> Option 1 </button>
                <button className = {this.addClass("btn2")} onClick = {this.changeColor.bind(this, "btn2")}> Option 2 </button>
            </div>
        </div>
    );
}

}

OptionButtons.css

.option {
    box-sizing: border-box;
    position: relative;
    margin-top: 655px;
    margin-left: auto;
    margin-right: auto;
    width: 80%;
    max-width: 650px;
}

.option .buttons {
    flex: 20%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.option .buttons button {
    flex-direction: row;

    border-radius: 5px;
    padding: 0 1.3rem;

    font-family: 'Nunito';
    font-style: normal;
    font-weight: 700;
    font-size: 1.2rem;
    line-height: 27px;
    text-align: center;

    width: 320px;
    height: 40px;
    left: 50px;

    cursor: pointer;
}

#option1Btn{
    margin-right: 10px;
}

.selected {
    color: "#fff";
    background-color: "#00867D";
    border: 1px solid "#00867D";
}

.notSelected {
    color: "#00867D";
    background-color: "#F2F2F2";
    border: 1px solid "#F2F2F2";
}

Result of my code

CodePudding user response:

I am not sure. did you say that when you click button 2, Its color will be changed and button 1 will be unchanged(active always)? or button 1 will be inactive?

https://codesandbox.io/s/priceless-tamas-yjr1lw?file=/src/Some.js

check it, do you want like this?

CodePudding user response:

You can easily change colors on button clicks in react:

const [backgroundColor, setBackgroundColor] = useState("white");
  const [buttonColors, setButtonColors] = useState({
    color1: "red",
    color2: "green"
  });

  const button1Clicked = () => {
    setBackgroundColor("gray");
    setButtonColors({
      ...buttonColors,
      color1: "green"
    });
  };

  const button2Clicked = () => {
    setBackgroundColor("green");
    setButtonColors({
      ...buttonColors,
      color2: "red"
    });
  };

  return (
    <div
      className="App"
      style={{
        backgroundColor
      }}
    >
      <button
        style={{ backgroundColor: buttonColors.color1 }}
        onClick={button1Clicked}
      >
        Button 1
      </button>
      <button
        style={{ backgroundColor: buttonColors.color2 }}
        onClick={button2Clicked}
      >
        Button 2
      </button>
    </div>
  );

You can find a working example here.

CodePudding user response:

There are a couple things that are not ok with your react code and CSS.

Number one you have elements with the property class instead of className.

Second, the color codes you are trying to attribute are strings ("#000"), so your browser doesn't know what to do with them. They should either be clear hexadecimals or using the rgb function.

I'll leave a Codesandbox using your component/CSS so you can take a look.

CodePudding user response:

I think what you are doing is just wrong and very confusing as there is a very elegant way to do it.

import React, {
  Component
} from 'react';
import './OptionButtons.css'

export class OptionButtons extends Component {
  constructor() {
    super();
    this.state = {
      selected: "btn1" //make this state a boolean so that it will turn true when you press button 1 and false when you press button 2 or vice versa 
    };
  }

  changeColor = (btn) => {
    this.setState({
      selected: btn
    });
  };

  //I have read it many times but I still don't understand what this function does in the code. In my opinion, it has no value to the action you are trying to achieve.  
  addClass = (btn) => {
    if (this.state.selected === btn) return "selected";
    else return "notSelect";
  };


  render() {
    return ( <
      div class = "option" >
      <
      h2 > Options < /h2> <
      div class = "buttons" >
      //it its better and easy to use a turnery operator rather than a function
      <
      button id = "option1Btn"
      className = {
        this.addClass("btn1")
      }
      onClick = {
        this.changeColor.bind(this, "btn1")
      } > Option 1 < /button> <
      button className = {
        this.addClass("btn2")
      }
      onClick = {
        this.changeColor.bind(this, "btn2")
      } > Option 2 < /button> <
      /div> <
      /div>
    );
  }

Instead, you can do like this

import React, {
  Component
} from 'react';
import './OptionButtons.css'

export class OptionButtons extends Component {
  constructor() {
    super();
    this.state = {
      selected: null //null so that when you click, you can assign a boolean value
    };
  }

  changeColorBtn1 = () => {
    this.setState({
      selected: true
    })
  }

  changeColorBtn2 = () => {
    this.setState({
      selected: false
    })
  }

  render() {
    return ( <
      div class = "option" >
      <
      h2 > Options < /h2> <
      div class = "buttons" >
      //I'm using turnery expression which means if selected: true then classname will be btn1 
      <
      button id = "option1Btn"
      className = {
        this.state.selected && 'btn1'
      }
      onClick = {
        this.changeColorBtn2.bind(this, "btn1")
      } > Option 1 < /button>
      //same as I did in the previous button but it's vice-versa
      <
      button className = {!this.state.selected && 'btn2'
      }
      onClick = {
        this.changeColorBtn2.bind(this)
      } > Option 2 < /button> <
      /div> <
      /div>
    );
  }

I hope it answers your question

  • Related