Deletion of an element with Reactjs upon clicking

A photo gallery consists of a collection of photos with corresponding delete buttons. Below is the HTML snippet for a gallery containing two images:

<div>
  <div class="image">
    <img src="URL1">
    <button class="remove">X</button>
  </div>
  <div class="image">
    <img src="URL2">
    <button class="remove">X</button>
  </div>
</div>

Develop the ImageGallery component which takes in a links prop and displays the above-mentioned gallery, where the first item in the links prop serves as the source attribute of the initial image in the gallery. The component should follow this rule: When a user clicks on the button, the associated image within the same div must be deleted from the gallery.

For instance, after removing the first image from the original gallery, it should appear like this:

<div>
  <div class="image">
    <img src="URL2">
    <button class="remove">X</button>
  </div>
</div>

I have devised a solution, however, it fails to pass all test cases

class ImageGallery extends React.Component {
  constructor() {
    super();

  }
  remove = e => {
    Array.prototype.forEach.call(
      document.getElementsByClassName("remove"),
      function(elem) {
        elem.onclick = () => elem.parentNode.remove();
      }
    );
  };
  render() {
    return (
      <div>
        {this.props.links.map((item, index) => {
          return (
            <div key={item} className="image">
              <img key={index} src={item} />{" "}
              <button className="remove" onClick={this.remove}>
                X
              </button>
            </div>
          );
        })}
      </div>
    );
  }
}

document.body.innerHTML = "<div id='root'> </div>";

const rootElement = document.getElementById("root");
const links = ["URL1", "URL2"];
ReactDOM.render(<ImageGallery links={links} />, rootElement);
document.querySelectorAll(".remove")[0].click();
console.log(rootElement.innerHTML);

View the sandbox demo - https://codesandbox.io/s/testdome-react-1-focus-7qbp1?file=/src/index.js

Refer to Question number 5 for specific details about the test cases -

Answer №1

here is the answer you are looking for

  class PictureGallery extends React.Component {
   constructor(props) {
       super(props);
       this.state = { images: props.images };
   }
   delete = index => {
      var list = this.state.images
      list.splice(index,1);
      this.setState({images:list})
     };

  render() {
    return (
     <div>
      {this.state.images.map((item, index) => {
       return (
        <div key={item} className="picture">
          <img key={index} src={item} alt="" />
          <button className="delete" onClick={() => this.delete(index)}>
            X
          </button>
        </div>
         );
       })}
     </div>
    );
   }
  }
    document.body.innerHTML = "<div id='app'> </div>";

  const appElement = document.getElementById("app");
   const images = ["www.example.com/image1", "www.example.com/image2"];
  ReactDOM.render(<PictureGallery images={ images } />,
            appElement);
  document.querySelectorAll('.delete')[0].click();
  console.log(appElement.innerHTML);

Answer №2

Instead of using external event listeners and removing DOM nodes manually, React provides a better way to handle these tasks. Here's an example:

Check out the updated sandbox: https://codesandbox.io/s/testdome-react-1-focus-4627z?file=/src/index.js

class ImageGallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = { links: props.links };
  }
  remove = url => {
    console.log(url)
    this.setState(state => ({
      links: state.links.filter(l => l !== url)
    }));
  };
  render() {
    const { links } = this.state;
    return (
      <div>
        {links.map((item, index) => {
          return (
            <div key={item} className="image">
              <img key={index} src={item} alt="" />{" "}
              <button className="remove" onClick={() => this.remove(item)}>
                X
              </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

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

Tips for avoiding template errors when retrieving data using Nuxt's fetch() method

After transitioning my vue app to a nuxt app, I encountered an issue with vue-slick-corousel. In the original vue app, everything worked smoothly with vue-slick-carousel, but after making the necessary modifications for nuxt, the carousel wouldn't dis ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Creating an array upon clicking and dynamically changing its class using AngularJS

Currently, I am developing a scheduling application where there are 2 individuals enrolled for 11 different dates. The functionality I am working on involves allowing the user to click on a month, which will then be added to an array and highlighted. If t ...

Refresh the three.js Raycaster when the window size changes

Currently, I am implementing a ray caster to choose objects within my three.js scene. The specific objects I am working with are box geometries shaped like flooring. After a successful selection of an object, I encountered an issue where resizing the wind ...

Is there a way to turn off autofocus in react-select?

Currently, I am using a selectbox from the "react-select" library. I am looking to implement a multi-select functionality without any wrapping as demonstrated in the sandbox provided. However, whenever I remove one of the chips or click on the input field, ...

Guide to displaying a text field and assigning a value to it upon selecting an option from a dropdown menu in a React application

I need help with displaying a textbox based on the selected value in a dropdown using React. Below is my code: <label> color: <select value="Radish" onChange ={this.checkColor}> <option value="Orange">Orange</option> <option va ...

Generate a JSON Object array by collecting data from various elements to make it dynamic

Seeking assistance in creating a dynamic array of JSON objects from the values of various elements. Below are some examples of these elements. There are more elements contributing to the JSON values, but I don't want to repeat the same code three time ...

Reorder children in a column layout with the top and bottom child elements reversed

I am attempting to create a layout using flex-direction: column-reverse in order to swap the positions of button 1 and button 2 without modifying the HTML: <button>2</button> <button>1</button> Unfortunately, I'm encountering ...

Material-UI React card grid

Hi there, I'm attempting to make it so that three cards are displayed in a row consecutively. I'm having trouble finding the right solution. ...

What are the different ways in which :style is utilized in re-frame - with brackets, curly brackets, or simply without any characters?

For my current project, I am utilizing Clojure, ClojureScript, lein, shadow-cljs, Emacs, and CIDER to develop a dynamic web application. Typically, when building the project, I initiate the command cider-jack-in-cljs in Emacs, select shadow-cljs, opt for ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

Tips for displaying external JavaScript code in an alert box:

Is there a way to display external JavaScript code in an alert or another location by accessing the variable value s_code? (function(){ var newscript = document.createElement('script'); newscript.type = 'text/javascript'; ...

Is there a way to extract data from the Redux state in a React component?

Seeking assistance with making an API request from Redux, followed by saving the data in my React state (arrdata). Although the API call is successful, I am facing challenges updating the App.js state based on the Redux API call. Any suggestions or insig ...

Attempting to modify the inner element through get element, but encountering a TypeError: Unable to assign value to 'innerHTML' property of null

I'm having trouble updating an element using the getElementById method and I keep getting this error message: TypeError: Cannot set property 'innerHTML' of null. Are there other ways to pass parameters or is this the right approach? This ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

What is the best way to assign a title to every div element and showcase 5 div items in a single line?

I am using a "for loop" to call getjson multiple times and receive a response to display items on sale inside a div. Currently, my code displays the item name to the right of each frame, but I want the item name to appear below the iframe, similar to the c ...

Are there any other potential factors that could lead to CSS files not being located within a Django project?

Apologies for asking the same question repeatedly. Despite trying for several days, I am unable to figure out where I went wrong. Can anyone provide guidance on my issue? I attempted to create a library program using Django. Below is the directory structu ...