Reactjs: When components are reused, conflicts may arise in UI changes

I'm currently working on creating a sample chat room application using reactjs and redux for educational purposes. In this scenario, there will be 3 users and the Message_01 component will be reused 3 times. Below is the code snippet:

const Main = React.createClass({
  render() {
    return (
        <div className="parentContainer">
            <Message_01 className="messageComponent" message={this.props.message} user="Bob" onMessageRemove={this.props.removeMessage} />
            <Message_01 className="messageComponent" message={this.props.message} user="Kevin" onMessageRemove={this.props.removeMessage}  />
            <Message_01 className="messageComponent" message={this.props.message} user="Stuart" onMessageRemove={this.props.removeMessage} />
        </div>
    );
  }
});

Message_01.js:

const Message_01 = React.createClass({
    sendMessage() {
        var msg = this.refs.msg.value;

        this.props.onMessageSend(this.props.user, msg);
        this.refs.msg.value = '';
    },

    keypress(event) {
        if (event.keyCode == 13) this.sendMessage();
    },

    onDoubleClickEvent(index, msgID) {
        var removeIcon = $('#' + msgID).find('.glyphicon-remove');

        if (this.props.message[index].User == this.props.user) {
            if (removeIcon.css('display') == 'none')
                removeIcon.css('display', 'block');
            else
                removeIcon.css('display', 'none');
        } else {
            console.log('you cannot get remove icon');
        }
    },

    removeMessage(index) {
        this.props.onMessageRemove(index);
    },

    render() {
        return (
            <fieldset>
                <legend>{this.props.user}</legend>
                {this.props.message.map((msg, index) => {
                    return (
                        <div key={index}>
                            <div className="chatContainer">
                                <div className="msgArea" id={msg.ID} onDoubleClick={() => this.onDoubleClickEvent(index, msg.ID)}>
                                <b>{msg.User}: </b> {msg.Message} <span className="timeSpan">{msg.Time}</span> <span onClick={() => this.removeMessage(index)} style={{ display: 'none' }} className="glyphicon glyphicon-remove" />
                                </div>
                            </div>
                        </div>
                    )
                })}
                <div className="MessageTyper">
                    <input type="text" ref="msg" className="message_typer" onKeyDown={(event) => { this.keypress(event) }} />
                    <button className="send" onClick={this.sendMessage}> Send </button>
                </div>
            </fieldset>
        );
    }
});

The current code setup results in three message containers as shown in the image below:

View Chat Room App

In the code, when a user double-clicks on a message instance, a remove icon should appear next to the message. However, there seems to be an issue where if the 2nd or 3rd component is double-clicked, the remove icon appears in the first component instead (as depicted in the image below). This behavior is incorrect.

View Result of the App

I would greatly appreciate any assistance with resolving this issue. Thank you in advance.

Answer №1

The root of this problem lies in the incorrect usage of a jquery selector. To resolve it, I need to use

var removeIcon =$($('#'+user).find('#' + msgID)).find('.glyphicon-remove');
instead of
var removeIcon = $('#' + msgID).find('.glyphicon-remove');
.

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

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

Incorporating text overlays on images that are compatible with responsive websites is a top priority for me

This is a piece of HTML code that utilizes bootstrap 3 for design purposes. The challenge faced is related to positioning text over an image. When resizing the browser, the alignment of the text with the background gets disturbed. Assistance is needed in r ...

Tips for recognizing a specific object ID within an array in order to modify the status of an element within that object

My goal is to accurately identify a specific panel within an expanded array and link that panel's ID to a button, while also ensuring the button is disabled when no panels are expanded or more than one panel is expanded. However, I am encountering iss ...

Encountering a Mongoose issue while attempting to load model files from a separate Mean.js project using the require function

I am currently working on a Mean.js project and in the process of familiarizing myself with this environment. To conduct some experiments, I created a parallel project for testing purposes in a separate folder where I am not using the Mean.js framework but ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

Utilizing DataTables to dynamically populate a table with data fetched from an AJAX request

I'm currently in the process of developing a program that showcases various topics within a specific subject. My main query revolves around whether or not the DataTable functionality will be compatible with this particular setup. The following is th ...

Support for ReactJS version 16.4 and Material UI version 4.x synergy

Encountering an issue while trying to run my project locally using React 16.4.1 and material-ui 4.1.1. The error message I am receiving is as follows: TypeError: _react.default.memo is not a function createSvgIcon c:/apps/projects/app/node_modules/@materi ...

Exploring the integration of React Context API within a Next.js application to streamline the authentication process

I am looking to build a react app using Next.js. However, I am currently stuck and need assistance in figuring out how to proceed. I have implemented user authentication on the backend with node.js, passport.js, passport-local-mongoose, and express.sessi ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

Transforming an image object into a File object using Javascript

My goal is to utilize HTML5 on the client side in order to convert an "image object" into a "File object" for uploading to azure blob storage. I am working with AngularJs and my approach involves: Converting the image to a file Uploading the file to blob ...

What could be causing these errors to pop up while attempting to install packages with `npm`?

Every time I attempt to use npm to install something, I always receive this type of message. discovered 7 vulnerabilities (3 moderate, 4 high) run npm audit fix to resolve them, or npm audit for more information Typically, I rely on create-react-app fo ...

PHP mistakenly outputs content that is not enclosed within tags

After discovering StackOverflow, I couldn't resist sharing my PHP code conundrum with the incredible community here! So, in a WordPress template, I have this chunk of PHP: echo '<div class="thumbnail">'; echo the_post_thumbnail(); ec ...

CSS/SCSS/JS: Adjusting header height dynamically while keeping it fixed at the

Check out my Codepen demo here: https://codepen.io/nickfindley/pen/dJqMQW I am seeking to replicate the current behavior of the page without specifying a fixed height for the header. The goal is to make the header adjust dynamically based on the content, ...

Diminish, then lead to a fresh page

I have encountered an issue with my code. The wrapper performs a fade out effect before redirecting the user to a URL. However, it only fades out once and I suspect this is due to the browser caching or loading the page quickly. Is there a way to ensure t ...

Ways to immediately display an uploaded image as the background on a canvas

Using TypeScript, I am attempting to set an uploaded image as the background of a canvas. However, I am facing an issue where the image only loads properly after the user has uploaded it two times. How can I ensure that the image has finished loading befor ...

Progressing with JavaScript: Implementing Sound Controls and Dynamic Image Switching

I am looking to create a button that, when clicked, displays a small image and plays a sound. The button should change to a different image and stop the sound when clicked again. Essentially, it functions as a "start" button that loops the sound and change ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Delay in Updating Nativescript Slider Value

After developing a metronome using the Nativescript Slider here to adjust speed (interval), I encountered an issue with incorrect updating of values. The code initially worked well, allowing real-time speed changes: app.component.html <Slider #sl min ...

Using Bootstrap to style the <option> element with RGBA colors

Struggling to figure this out and seeking assistance. I have a form using bootstrap where I can apply rgba color for my select tag but not for the options. Select CSS: select { background-color: rgba(0,0,0,0.25) !important; border: 1px solid rgba ...

Chrome not displaying Bootstrap dropdowns correctly

Lately, I've been exploring Bootstrap and experimenting with its dropdown menus. Typically, I use Chrome for my work but encountered a strange issue with how Chrome is handling my dropdown menus. This forced me to temporarily switch to Edge. Here&apos ...