What is the best way to retrieve an element that has been altered in its state?

I encountered a scenario where I want an image to have a border when clicked, and if clicked again, the border should be removed. However, the border should also be removed if another image is clicked instead.

I believe there are a couple of approaches to tackle this issue, but I am unsure how to actually implement them:

  1. Resetting borders for all images
  2. Maintaining previous state to identify the element

I am utilizing states that are passed down from ancestors, so I may not be able to share all the scripts - I'll attempt to provide snippets instead.

The images: using 'next/image'

    return(
        <div key={attr} id={attrprops.attrChoice+':'+attr}>
        <Image
            src={imgSourceUrl}
            alt={attrprops.alt}
            width={attrprops.w}
            height={attrprops.h}

            onClick={()=>{  attrprops.setButtonClick(!attrprops.buttonClick);
                            attrprops.setBorder(attrprops.selectedAttr==attr ? false : true);
                            attrprops.setSelectedAttr(attr);
                        }}
        />
        <br></br>
        <div className='flex justify-center align-center'>{attr}</div>
        </div>
    );

State change logic:

useEffect(()=>{
    if (border&&buttonClick){
        document.getElementById(`body_type:${selectedAttr}`).className = 'border-2 border-blue-500';
        publishprops.setAttrNumber(4);
    }
    else if (!border&&buttonClick){
        document.getElementById(`body_type:${selectedAttr}`).className = 'border:none';
        publishprops.setAttrNumber(2);
    }
},[border])

Currently, only selected images receive borders. Unsure about the best approach to follow for achieving the desired functionality...

Answer №1

To effectively utilize React, it is essential to adjust your mindset regarding state management. Your code should be easy to read and understand the intent behind it.

From what I see, your example appears to be quite simple. It's either showing a highlighted image or none at all.

Here is a more straightforward example you can consider:

import React, { useState } from 'react';

const images = [
    '1.png',
    '2.png',
    '3.png',
    '4.png',
    '5.png',
];

const MyComponent = () => {
    const [selectedImage, setSelectedImage] = useState(null);

    return (
        <ul>
            {images.map(src => (
                <img
                    key={src}
                    className={`
                        my-image
                        ${selectedImage === src ? 'active' : ''}
                    `}
                    onClick={() => setSelectedImage(
                        selectedImage => (
                            selectedImage !== src
                            ? src
                            : null
                        )
                    )}
                />
            ))}
        </ul>
    );
};

When selectedImage is null, it means no image has been clicked. Upon clicking, we either set it as the clicked image or revert it back to null if the same image is clicked again. The border styling is applied using the active class in CSS:

.my-image {
    border: 5px solid transparent;
}

.my-image.active {
    border-color: red;
}

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

What steps are involved in bundling a Node project into a single file?

Recently, I've been using npm to create projects. When it comes to AMD, I find the native node require to be very convenient and effective for my needs. Currently, I rely on grunt-watchify to run my projects by specifying an entry file and an output f ...

Parameter for Ajax URL

As a beginner in the world of Ajax, I'm on a mission to grasp the inner workings of this technology. I came across a tutorial on w3schools that sparked my curiosity. In the code snippet below, the 'url' is defined as demo_ajax_load.txt. Wil ...

The routing in NextJS takes into account both the forward slash (/) and the encoded forward slash (%

I have a URL that looks like this: manage/text_U2FsdGVkX1/7AucFzVPX7OpRHb8Dlk/ApiJsTvYroROv4Ds4oshwC+cg3a7Mz/aO This URL needs to be processed by the route/directory /pages/manage/[id] The ID is test_someEncryptedString However, because of the forward s ...

What is the process to alter the IconComponent of a NativeSelect based on whether it is open or closed?

In my customization of NativeSelect (in Material UI v3), I am aiming to dynamically change the IconElement based on whether the NativeSelect is open or closed. Unfortunately, it appears that using the open, onOpen, or onClose props with NativeSelect is not ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Next js is throwing an error because it cannot accept objects as a React child. Instead, it found an error message stating "Response not successful: Received status code 401."

This app showcases Github issues by utilizing the graphql API. After finishing the app, I encountered an error without making any changes. The technologies used for this project include Next.js, Typescript, Material UI, Tailwind CSS, and GraphQL. https: ...

The React Router Dom V6 triggers loaders as soon as the router is initialized

I'm currently working on implementing routing into my application using react-router-dom V6, specifically utilizing the new createBrowserRouter function and RouterProvider component. The issue I'm facing is that when attempting to integrate a lo ...

Tips for preserving changes made to a jQuery script when the page is reloaded

Is there a way to retain jQuery script changes when the page is reloaded? I have a page where clicking on certain elements triggers events, and I want these changes to persist even after reloading the page, resetting only when the cache is cleared. I appre ...

Inject additional information following user authentication

Hello there! I have successfully developed a REST API using Node.js and StrongLoop, along with an Angular.js based app. After a user logs in, the server sends an accessToken which is stored in cookies. For every request, the accessToken is sent and verif ...

A React component enclosed within a useCallback function

According to the React docs, to prevent a Child component from re-rendering in certain cases, you need to wrap it in useMemo and pass down functions in useCallback within the Parent component. However, I'm confused about the purpose of this implementa ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

Having trouble with $addToSet and $push not working in updates using Mongoose with MongoDB in Node.js?

My issue involves Mongoose as I am attempting to update a document in MongoDB using the mongoose module. Below is my schema: var User = new mongoose.Schema({ name: String, email: String, list_houses: [{ id_house: S ...

"Embracing Micro-frontends: Building dynamic web applications using a variety of frontend

I am currently facing a software architecture dilemma. My extensive monolithic web application is built using PHP and backbone js, but I am eager to integrate a new front-end framework like react/vue. The question arises about the best approach to tackle t ...

What is the best way to eliminate query parameters in NextJS?

My URL is too long with multiple queries, such as /projects/1/&category=Branding&title=Mobile+App&about=Lorem+ipsum+Lorem+. I just want to simplify it to /projects/1/mobile-app. I've been struggling to fix this for a week. While I found so ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

Optional parameters in Sammy.js

Utilizing ajax for paging has led me to choose Sammy.js, which works well. However, incorporating checkboxes to filter results poses a challenge. While defining a route for Sammy to intercept is feasible, the issue arises when I wish to avoid displaying ce ...

Using the splice() method to remove an item from an array may cause unexpected results in React applications

Dynamic input fields are being created based on the number of objects in the state array. Each field is accompanied by a button to remove it, but there seems to be unexpected behavior when the button is clicked. A visual demonstration is provided below: ...

Is there a way to update a JSON key using the "onchange" function in React?

I'm facing an issue. I have a form with two inputs. The first input is for the key and the second input is for the value. I need to update the values in the states whenever there is a change in the input fields, but I'm unsure of how to accomplis ...

TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map. let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test ...