Ways To Eliminate Image Tags From Being Displayed

I want to create an onClick function that will remove the most recently added image from the input array and prevent it from displaying.

Check out my code below:

<div>
  <form>
    <input type="file" name="pic" accept="image" onChange={this.handleClick} multiple />
    <input type="submit"/>
    <button className={"clear"}>Clear last image</button>
  </form>
</div>
<div style={formStyle}>
  {this.state.array.map((item, i) =>
    <img
      style={imgStyle}
      src={URL.createObjectURL(item)}
      key={i} 
    />
  )}
</div>

In this snippet, I capture a user's uploaded image file and store it in a state array before displaying it. While there isn't a direct post addressing this issue, I am curious if anyone knows how to efficiently remove the last uploaded image tag from the DOM?

Answer №1

You can easily update the state by removing the last item from the array

clearLast = (e) => {
  e.preventDefault();
  this.setState({
    array: this.state.array.slice(0, -1)
  });
}

--

<button className={"clear"} onClick={this.clearLast}>Clear last image</button>

edit with changes above

Since the button is part of a form, clicking it may cause the form to submit. Use e.preventDefault() to prevent this behavior.

Alternatively, you can simply add type="button" like:

 <button type="button" className={"clear"} onClick={this.clearLast}>Clear last image</button>

This way, the form will not be submitted inadvertently.

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

In the realm of web development, the Phoenix library introduces the concept

Is there a way to combine a dynamic classname and a static one effectively? <div class=<%="#{getClass(app.status)} two" %> What happens is <div class="one" two> Instead of the desired output of <div class="one t ...

Duplicating information within a row

Why am I seeing the same value in all rows of the table? Each row in the table can be clicked to reveal additional information, but every row displays the data from the last clicked row. This issue may be due to saving data in the same object. Unfortunatel ...

Guide to Indicating an Icon in Front of an HTML Link and Emphasizing Both with Tap

When using an iOS UIWebview, I am facing the issue of needing to add an icon before standalone links that are within a locally loaded HTML file. In addition to adding the icon, I also need both the icon and link to be highlighted when tapped. The desired ...

Text adornments persisting even after formatting removal (underline disappears, but text remains embellished)

I included a link within a div and applied text-decoration: none; to the anchor tag as shown below: Here is the CSS (SCSS) code snippet used: &__link { &:link, &:visited { text-decoration: none; } } And here is the corres ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Exclusive CSS banner slider glitch - Hyperlinked images unresponsive

.zd-slider { position:relative; overflow:hidden; margin-top: 0px; } .zd-slider img[id*="img"] {width:100%; position:absolute; left:0; top:0; opacity:0; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";} /* Set the width/height of the slide ...

Guide to dynamically generating checkboxes or multi-select options in ASP.NET MVC 4

Within this project, we have implemented two separate lists - one for the dealer and another for their products. Currently, when selecting a specific dealer, all associated products are returned using JavaScript (Json). Utilizing Html 5: @using (Html.Be ...

Passing on Query Params in NextJS from Previous Page

Is there a way to automatically pass the parameter from the current URL to the next URL when the router changes? For example: Current URL: localhost:3000/dashboard/?name=abc When moving to the page /profile, I would expect the new URL to be like th ...

Struggling to set up the API connection between the ReactJS frontend and the NodeJS/Express backend in my project

Currently, I'm working on integrating a React application with a database. It seems like the best way to achieve this is by using nodejs/express as a backend. To ensure proper communication between my React app and the backend, I added a proxy entry i ...

Mapbox struggling with performance because of an abundance of markers

I have successfully implemented a feature where interactive markers are added to the map and respond to clicks. However, I have noticed that the performance of the map is sluggish when dragging, resulting in a low frame rate. My setup involves using NextJ ...

Would Django be the right fit for the project I have in mind?

Although I have experience with HTML/CSS/Javascript and Python individually, I find myself at a loss when it comes to combining them. I am unsure if it's even possible. I have a Python script that can take input, perform calculations, and return a val ...

Exploring the depths of CSS line-height

Have you noticed the difference in line height between these two paragraphs on Safari and Chrome? Shouldn't the default line height be 1.0, representing the "natural" height of a particular font (where descenders from the line above do not clash with ...

A guide on parsing a React file (ES6 with JSX) using Node.js to extract the exported variable

When attempting to read the react file containing the router, I encounter a node crash error (I am trying to build a sitemap but even when I simply attempt to console.log the export default variable, I get this error - maybe it requires babel configuration ...

React Native App experiences immediate crashes when launched on TestFlight

I've encountered a frustrating issue with my application that keeps crashing when loaded into Testflight. To troubleshoot, I decided to start from scratch and created a basic expo react native application to pinpoint the source of the problem. After ...

The ng-change function is successfully executed only when the user presses the backspace key or enters

<input type="email" ng-keypress="testFunc()" ng-model="text" id="femail" class="form-control margin" name="femail" placeholder="Email*"/> <p style="color: red;">The input field has changed {{count}} times.</p> JS $scope.count = ...

Having trouble incorporating a new translation into the common namespace of next-translate in Next.js

[next-translate] "common:removed_shareholder" is missing in the current namespace configuration. Consider adding "removed_shareholder" to the namespace "common". Attempting to include additional translations in my common.json ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Prevent distorting images by avoiding stretching them beyond

I am encountering an issue with the image tag on my page. It is set to a height of 300px, but when a larger image is used, it gets stretched and looks distorted. Is there a way to only display a portion of the image, specifically the top 300px? I hope my ...

Attempting to invoke the layout() function through ResizeObserver proves ineffective, whereas triggering it through window.onResize yields successful results

Within my react application, I have an array called editors which contains all editors that have been created using the monaco.editor.create() method and are currently open in the application. Here is a snippet of my code: const resizeObserver = useRef(new ...

Is there a way to navigate to react-router from express?

I am currently implementing authentication in my application, which utilizes react-router. While following the auth-flow example in react-router as a reference, I decided to use passport instead of localstorage. Thankfully, everything is functioning proper ...