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 -