Having trouble updating the text in a div tag located above a specific button?

Hey there! I am using a RoundedButton component with a div tag for setting dynamic text, followed by a button.

In my App.js, I have utilized this component thrice. However, when a user clicks on any button, the "User selected" text should display above that specific button. Currently, it is only showing above the first button regardless of which button is clicked.

RoundedButton.js

class RoundedButton extends Component {
  constructor(props) {
    super(props);
  }

  _handleButtonClick(item) {
    this.props.clickitem(item.buttonText);
    //document.getElementById("who_played").innerHTML = "User selected";
  }

  render() {
    let buttonText = this.props.text;
    return (
      <div className="WhoPlayed">
        <div id="who_played" style={{ marginLeft: 5 }} />
        <div>
          <button
            type="button"
            className="Button"
            onClick={this._handleButtonClick.bind(this, { buttonText })}
          >
            {buttonText}
          </button>
        </div>
      </div>
    );
  }
}

export default RoundedButton;

App.js

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import RoundedButton from "./RoundedButton";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "./actions/index";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      score: 0,
      status: ""
    };
    this.clickitem = this.clickitem.bind(this);
  }

  clickitem(user) {
    var url = "http://localhost:4000/generate-random";
    document.getElementById("who_played").innerHTML = "User selected";
    fetch(url)
      .then(response => {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(data => {
        var computer = data.item;
        if (
          (user === "Rock" && computer === "Scissors") ||
          (user === "Paper" && computer === "Rock") ||
          (user === "Scissors" && computer === "Paper")
        ) {
          this.props.increment();
        } else if (user === computer) {
          this.props.doNothing();
        } else {
          this.props.decrement();
        }
      });
  }

  render() {
    return (
      <div className="CenterDiv">
        <div className="AppTitle">
          <b>Score: {this.props.score}</b>
          <div>
            <RoundedButton text="Rock" clickitem={this.clickitem} />
            <RoundedButton text="Paper" clickitem={this.clickitem} />
            <RoundedButton text="Scissors" clickitem={this.clickitem} />
          </div>

          <div className="Status">{this.props.status}</div>

        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

export default connect(mapStateToProps, actions)(App);

Current Status:

https://i.sstatic.net/zqzDS.png

Expected Result:

https://i.sstatic.net/Pta7M.png

Any advice on what could be going wrong here?

Answer №1

There are a few key issues to address in the provided code snippet:

  1. The HTML output contains multiple instances of RoundedButton, each containing a div element with the same id attribute of "who_played". In HTML, IDs should be unique within the document to avoid conflicts. To resolve this, ensure that each button has a distinct and unique ID for proper functionality.
  2. Given the declarative nature of React, utilizing the DOM API to set labels is not recommended. Instead, leverage state management for handling dynamic content updates. Here's an example implementation:

    class App extends Component {
        constructor(props) {
            super(props);
            this.state = {
                score: 0,
                status: "",
                selected: ""
            };
            this.clickitem = this.clickitem.bind(this);
        }
    
        clickitem(item) {
            this.setState({ selected: item });
            ...additional code...
        }
    
        render() {
            return (
               <div className="CenterDiv">
               <div className="AppTitle">
                   <b>Score: {this.props.score}</b>
                   <div>
                   <RoundedButton text="Rock" clickitem={this.clickitem} selected={this.state.selected === "Rock"} />
                   <RoundedButton text="Paper" clickitem={this.clickitem} selected={this.state.selected === "Paper"} />
                   <RoundedButton text="Scissors" clickitem={this.clickitem} selected={this.state.selected === "Scissors"} />
                   </div>
    
                   <div className="Status">{this.props.status}</div>
    
               </div>
               </div>
           );
       }
    }
    
    class RoundedButton extends Component {
       _handleButtonClick(item) {
           this.props.clickitem(item.buttonText);
       }
    
       render() {
           let buttonText = this.props.text;
           return (
               <div className="WhoPlayed">
               <div id="who_played" style={{ marginLeft: 5 }}>{this.props.selected ? "User Selected" : ""}</div>
               <div>
                   <button
                   type="button"
                   className="Button"
                   onClick={this._handleButtonClick.bind(this, { buttonText })}
                   >
                   {buttonText}
                   </button>
               </div>
               </div>
           );
       }
    }
    

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

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Ways to position an absolute element in the middle of two CSS Grid cells

Is it possible to position an element with position: absolute between two grid cells, where half of the element is on the sidebar and the other half is on the rest of the page? The challenge arises when there is overflow set on both the sidebar and the pag ...

The error message "TypeError: Cannot access the tapAsync property because it is undefined"

"webpack": "^7.89.0", "webpack-cli": "^6.2.8", After updating webpack to the versions above, I encountered this error: clean-webpack-plugin: /home/itrus/react/living_goods/build has been removed. TypeError: Cannot r ...

Delete the strings in the array once the checkbox is unchecked

I have some data for my checkbox here, $scope.dataList = { 'ICT': true, 'OTTIX_DT': true, 'CP EMR AD': true, } <input type="checkbox" ng-model="miniAddons.dataList[data.jobName]" ng-change=& ...

Iterating through object using jQuery

I'm facing an issue with iterating through a JSON object for the first time. The JSON is structured like this: { "response": { "2012-01-01": { "Available": 99, "Variations": [ { ...

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Safeguarding intellectual property rights

I have some legally protected data in my database and I've noticed that Google Books has a system in place to prevent copying and printing of content. For example, if you try to print a book from this link, it won't appear: How can I protect my ...

What is the best way to extract a specific data field from an XML tag?

The format of the XML I'm currently handling is as follows: <item> <title>$39.99 and Under Juniors' Swimwear</title> <link>http://www.amazon.com/s/ref=xs_gb_rss_A1RFRNENBWTVO4/?rh=n:1036592,n:!2334084011,n: ...

Having trouble with next.js website not displaying correctly on mobile devices

I obtained a website template from the internet, and I was not satisfied with how it was converted to TypeScript for my next project in order to easily deploy it on Vercel. However, when I switch to mobile mode using Chrome developer tools, I encounter the ...

Establishing the development environment

As a recent Computer Science graduate, I am currently employed at a startup where I have been assigned the task of integrating new features into purchased software. The software was obtained from AWS and my initial attempts to work on it have been challeng ...

Componentizing Vue for Better Reusability

Currently tackling a large application filled with legacy code, I'm facing a repetitive issue that has popped up twice already. It's becoming clear to me that there must be a more efficient way to solve this problem. Here's what I'm dea ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

The absence of a type annotation for `T` has been noted

Attempting to create code with a simple JavaScript function: filterArray(user: any, items: Array<Object>) { items = items.filter(item => {return true;}); return items; } Encountering the following error: Error message: Missing type anno ...

How can I stop the toolbar from showing up when navigating between pages on an iPad with IOS?

We recently encountered an issue with our web app that is installed on the home screen of iPads for a more app-like user experience. The problem started after the latest iPadOS update, causing a disruption in the UI where a minimal version of the Safari to ...

Unlocking the secret to transferring information from POJO and Controller to Ajax

I have a situation where I am sending data from my controller as Json using the @ResponseBody annotation. Unfortunately, I am facing an issue where ajax is unable to recognize the data sent from my controller. When I check the typeof data in ajax, it shows ...

Having trouble using the elementIsNotVisible method in Selenium WebDriver with JavaScript

I'm struggling to detect the absence of an element using the elementIsNotVisible condition in the Selenium JavaScript Webdriver. This condition requires a webdriver.WebElement object, which is problematic because the element may have already disappear ...

Ensuring uniform div heights using jQuery

Currently attempting to use jQuery to equalize the heights of my divs, but it seems to only match the height of the smallest column. I actually want it to match the height of the tallest column. According to the code I have written, it should find the tall ...

Attempting to prompt a second activity by clicking a button

My current project involves developing an android app that includes launching a second activity from a button click in the main activity. However, I'm encountering the following error: Error Cannot Find Symbol Method startActivity(Intent) I've h ...

What is the reason behind React deciding to skip the final question, even though it has been accurately saved to the

A simple web application was developed to calculate risk scores by asking five questions, with additional points awarded if a checkbox is checked. Despite extensive hours spent debugging, a persistent bug remains: the final question does not appear on the ...

Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written: <!doctype html> <html lang="en"> <head> <title>Testing form input</title> <style type="text/css></style> <script type="text/javascript" src="validation.js"></script> &l ...