React Bootstrap ToggleButton firing function multiple times unnecessarily

I've encountered an issue with my react-bootstrap ToggleButtons. Whenever I click on them, the handlePlatformChange() function is triggered twice - first with the correct id and then immediately after with null. I tried including e.preventDefault() in the function, but it caused the buttons not to toggle properly. I've tried everything I can think of, so any advice would be greatly appreciated.

import React, {Component} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import Button from 'react-bootstrap/Button';
import ToggleButton from 'react-bootstrap/ToggleButton';
import ToggleButtonGroup from 'react-bootstrap/ToggleButtonGroup';

class App extends Component {
  constructor () {
    super();
    this.state = {
        User : "",
        Platform: "battle",
        Player: "",
        Level: ""
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handlePlatformChange = (e) => {
    this.setState({Platform: e.target.id}, function () {
      console.log(this.state.Platform);
    });
  }
    
    
  handleChange(e) {
    if (e.target.id === "usernameinput") {
      this.setState({User: e.target.value});
    }
  }

    render() {
        return (
          <div className="infoSection">
          <div className="center">
            <input type="text" id="usernameinput" value={this.state.value} onChange={this.handleChange} placeholder="Username" /><br/>
            <ToggleButtonGroup id="buttongroup" name="buttongroup" defaultValue={[1]}>
              <ToggleButton id="battle" value={1} variant="secondary" onClick={this.handlePlatformChange}></ToggleButton>
              <ToggleButton id="acti" value={2} variant="secondary" onClick={this.handlePlatformChange}></ToggleButton>
              <ToggleButton id="psn" value={3} variant="secondary" onClick={this.handlePlatformChange}></ToggleButton>
              <ToggleButton id="xbl" value={4} variant="secondary" onClick={this.handlePlatformChange}></ToggleButton>
            </ToggleButtonGroup>
            <br/>
              <Button id="searchButton" variant="primary">Search</Button>
              <div className="displaySection">

                <p id="displayHeader">Username: {this.state.Player}<br/>
                Level: {this.state.Level}</p>
                <p id="displayInfo1">some info here</p>
                <p id="displayInfo1">some info here</p>
              </div>
          </div>
          </div>
        );
}
}

export default App;

Answer №1

When dealing with your ToggleButton element, it's important to note that it is actually comprised of an input nested inside a label. If you were to represent this element in plain HTML, it would look something like this (here's an example for the first button):

<label id="battle" variant="secondary" type="button" class="btn btn-default active"
  <input type="radio" name="buttongroup" autocomplete="off" value="1"></input>
</label>

While the id you want is on the label tag, clicking the input will only target the input tag itself.

To address this issue, you will need to adjust your handlePlatformChange method as follows:

handlePlatformChange = (e) => {
    this.setState({Platform: e.target.parentNode.id}, function () {
      console.log(this.state.Platform);
    });
  }

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

Button for AngularJS delete request

I have developed a live polling application that allows users to create, view, and delete questions from the table pools stored in the RethinkDB database. The issue lies with the delete functionality. While sending a DELETE request using POSTMAN successfu ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

Exploring the possibilities of ReactJS and the sleek design of

How can I alter the background color of a RaisedButton without having the CSS class name appear in the autogenerated div? Here is the button: <RaisedButton className="access-login" label="Acceder" type="submit"/> This is the specified CSS: .acces ...

Is it possible to use the googleapis npm package to make a query to a googleSheet?

I have a huge dataset with thousands of rows and I want to optimize my queries instead of fetching all the data every time. I checked out the Query language but it doesn't quite fit my needs. For authentication, I am using a Service account: const au ...

What could be preventing my logo from properly resizing with html/css?

* { box-sizing: border-box; padding: 0; margin: 0; } ul { list-style-type: none; } .nav-links, .logo { text-decoration: none; color: #000; } .logo { max-width: 80%; width: 20%; height: 20%; } .navbar { padding: 20px; height: 50vh; ...

Issue with NPM identifying my module (demanding unfamiliar module)

Currently, I am developing a React-Native application and organizing my components into separate files. Most of the time, this method works perfectly fine except for one specific instance where I keep encountering a 'Requiring unknown module' err ...

Could the quantity of JavaScript files impact the performance of a project and cause any delays?

In my current HTML and JavaScript project, I am incorporating multiple JavaScript files. I'm curious to learn about the potential impact of having numerous JavaScript files on a web project's efficiency and speed. Can anyone shed some light on th ...

Is there a way to horizontally center a content container in Flutter similar to a "max-width" container in CSS?

How can I create a centered content box like this in Flutter?: .content-box { margin-left: auto; margin-right: auto; width: 100%; max-width: 600px; background-color: blue; height: 100vh; } <div class="content-box"> Cont ...

What causes a significant influx of packages each time I execute the command `npm install`?

https://i.sstatic.net/a3BxV.png https://i.sstatic.net/dcVXS.png Could this be related to my overall package.json file? ...

Can we incorporate <a> tags in XML as we do in HTML?

Currently, I am honing my XML skills. I am planning to incorporate the <a> tag within the XML file in order to create a hyperlink to another webpage. ...

JS filter function is not functioning as expected. It's unclear what the issue might be

Check out my previous inquiry What could be the issue with my filter? I've implemented a filter, but it seems to have some glitches when dealing with specific values. The 'No Record Found' message doesn't appear as expected in certain ...

Serve react JS files using Express JS

Combining my express js backend with my react js frontend into one project is my current goal. I'm curious if it's feasible to create a task using tools like webpack or grunt to compile the react js code first and then automatically transfer the ...

What is the best way to manage feedback on various posts?

I am struggling to retrieve individual posts as it appears that I am only able to access the first one. Is there a way to uniquely identify each post using PHP and then retrieve the same value with JavaScript? Alternatively, I am open to any other solutio ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...

How can I retrieve the Axios error response object within a catch block?

After recently updating to axios version 0.23.0, I encountered an error when attempting to access the error response object in a catch clause. Here is where the issue arises: const loginUser = async (userData: UserPayload): Promise<void> => { ...

Setting up a CentOs Linux environment to host and run a node.js server

Just installed node.js on my new VPS server. I have written a basic script called "server.js" and it is currently running on port 8080. The location of the script is in the "var/www/html/" directory. However, whenever I try to access my domain, it only dis ...

Tips for customizing compound components in Mui using 'classes'

Is there a way to customize Mui styles using the classes prop? One example is overriding the color of the InputLabel in the TextField component. I want to define makeStyles that will apply css rules starting at the root and override specific elements, li ...

Is there a advantage to using Angular's component style encapsulation for improved performance?

Recently, I came across the styling methods of Angular 2 which allows you to directly include your styles within the component. If you want to explore more on this topic, check out loading styles. There are two options for style encapsulation in Angular 2 ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

What is the proper procedure for entering data in the correct sequence using JavaScript?

I am currently utilizing Node.js to send data to a SQL Server table. Within the code, there is a for loop that calls a function triggering an insert statement (which will eventually transition to being a stored procedure). This loop iterates through variou ...