Switch between two button designs in a React JS application

Is it possible to have the style of a button change when clicked? Specifically, I would like the option 1 button to be selected and have its background color changed by default. If I click on the option 2 button, I want only that button to change while leaving option 1 unchanged.

After following the method outlined in this post, I encountered an issue where my buttons were not displaying the desired colors as expected.

Below is a snippet of 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>
    );
}

}

Then in 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";
}

To view the result of my code, click here.

Answer №1

Are you saying that when button 2 is clicked, its color will change while button 1 remains unchanged (always active)? Or will button 1 become inactive?

https://example.com/some-link

Take a look and let me know if this is what you're looking for.

Answer №2

Modifying colors based on button clicks in react is a breeze:

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

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

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

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

Check out this live demo for reference.

Answer №3

Your React code and CSS could use some adjustments for better functionality.

First, make sure to use className instead of class for elements in your code.

Also, ensure that the color codes you are using are either clear hexadecimals or utilize the rgb function for proper representation in the browser.

Feel free to check out this Codesandbox link with your component/CSS for further reference.

Answer №4

It seems to me that your approach is somewhat misguided and could be simplified for better clarity.

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

export class OptionButtons extends Component {
  constructor() {
    super();
    this.state = {
      selected: "btn1" //transform this state into a boolean value that switches when different buttons are clicked 
    };
  }

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

  //After reviewing this function multiple times, I find it redundant and unnecessary for the intended purpose of the code.
  addClass = (btn) => {
    if (this.state.selected === btn) return "selected";
    else return "notSelect";
  };


  render() {
    return ( <
      div class = "option" >
      <
      h2 > Options < /h2> <
      div class = "buttons" >
      //Consider using a ternary operator instead of a separate 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>
    );
  }

Alternatively, you could simplify the implementation like this:

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

export class OptionButtons extends Component {
  constructor() {
    super();
    this.state = {
      selected: null //initialize as null to assign a boolean value upon clicking
    };
  }

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

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

  render() {
    return ( <
      div class = "option" >
      <
      h2 > Options < /h2> <
      div class = "buttons" >
      //Utilizing a ternary expression for conditional rendering
      <
      button id = "option1Btn"
      className = {
        this.state.selected && 'btn1'
      }
      onClick = {
        this.changeColorBtn2.bind(this, "btn1")
      } > Option 1 < /button>
      //Similar approach with opposite conditions
      <
      button className = {!this.state.selected && 'btn2'
      }
      onClick = {
        this.changeColorBtn2.bind(this)
      } > Option 2 < /button> <
      /div> <
      /div>
    );
  }

Hopefully, this provides some clarity on the matter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Select any menu option to return to the one-page layout and then scroll down to find the location

I'm wondering if there is a way to navigate back from an external page to a specific section on my one-page website with a fixed menu? On my one-pager website, I have a fixed menu that includes a "apply for a job" button. When clicked, it takes users ...

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Is it a mistake? Using React and ES6 without Babel may not be the

Have you ever considered bundling all of your classes into a single file without using Babel to polyfill it to ES5? If the browser doesn't support ES6, you could then use Babel in the browser or load the polyfilled bundle and manually add the dependen ...

Expo SDK is essential for the proper functioning of Expo. It is required to run React Native built APK files

After developing my app using Expo, I successfully ran it on both iOS and Android emulators. However, when attempting to generate an APK file with the cd android && ./gradlew assembleRelease command, everything seemed fine at first. But upon insta ...

Utilizing React components from npm in Rails: A comprehensive guide

Recently delving into the world of react, I came across an insightful article on integrating React with Rails at . The transition was seamless until I attempted to incorporate Summernote (a WYSIWYG html editor) into my records.html page. Despite discoverin ...

A guide on accessing JSON data with ReactJS

Seeking assistance with fetching data from a JSON using React JS. As a beginner in learning React, I am curious about the methods available to fetch data from a complex JSON structure. I have referred to the React Tutorial but am facing challenges in fetc ...

Switching the background image when hovering over a list element

Looking at the screenshot, it's clear that there is an unordered list with a background image set on the div. What I am trying to achieve is to have the background image change whenever I hover over a list item. Each list item should trigger a differe ...

Is it possible to display an item within another item?

Is there a way to select the data within the 'posts' table while having relations set up for the users table & posts table? I'm not entirely sure how to go about it. Here is the Console Data that I am referring to. This is my usual meth ...

Incorporating nested maps in JSX for efficient data manipulation

{normalizedData.map(item => <div key={item.display_date_numberic}> <div>{item.display_date_numberic}</div> </div> {!isEmpty(item.applicants) && item.applicants.map(applicant => <div className= ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

Conceal an element using a transition effect, initiating its positioning at the center instead of the default

One of the challenges I'm facing is with a video element that I want to hide gradually when clicking on another element. The issue is that after the animation completes, the video ends up hidden at the top-left corner of the screen instead of at the c ...

The 'float' property in HTML and CSS

Good day everyone! I apologize in advance if my explanation is not very clear. Below is my code along with a link to an image that will help illustrate the issue I am facing. Here is the code snippet: <header> <div> <a href="index.html ...

Toggling checkboxes based on user input

My dynamic table is filled with checkboxes that can be checked or unchecked. I have created a jquery script that should change the background color of the table cell whenever a checkbox is modified. However, the script seems to have some bugs and doesn&apo ...

Is it necessary for React to have NodeJS in the frontend environment?

As a newcomer to the world of React, I am eager to create a simple hello world example from scratch. While most tutorials provide a standard setup involving nodeJS and npm, I decided to take a different approach: app.js var reactElement = React.createEle ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Challenges encountered when assigning values in a form with Material UI, Formik, and Typescript

When attempting to set the 'role' and 'active' values on a form, I encountered a couple of issues. The first problem arises from the fact that the selectors' original values are not being properly set. These values are fetched in ...

Cookies are not persisting in the browser even after successful login on a React Node.js application deployed on Render hosting platform

I recently completed a Full-stack MERN (React + Node.js + MongoDB) project by following a tutorial on YouTube. You can check out the tutorial here. The official GitHub repository for this project can be found at https://github.com/codinginflow/MERN-course ...

Using a CSS nth-child selector to eliminate the bottom margin of the final row

As I work on creating lists that are displayed in columns of two, each .customer-review-container includes a margin-bottom CSS property like this: <div class="col-md-6"> <div class="customer-review-container"> </div> <!-- en ...

Struggling to get custom CSS to apply properly in Joomla 4 with Bootstrap 5 template

Having created a simple Bootstrap 5 template for my Joomla 4 website, I've been attempting to customize the navbar with CSS in my user.css file. However, it seems that the styles added in user.css are not being applied. I have verified that user.css ...

Iconic Material Design from Material-UI

Adding an icon button in the form of a star and wanting to fill it with a solid color on click. import StarIcon from '@material-ui/icons/StarBorder' ... <IconButton><StarIcon className={classes.favoricon}/></IconButton> I sear ...