I am making a local web app where on click, a new image is created inside the src folder. I want my web page to update an <img> tag's source with the path of the new image. If I just change the src dynamically with the React state no image ever loads, however using inspect element I can see that the correct path is passed. (This way of changing the image worked before I started using Parceljs).
The first image only loads when I import it. However I don't know if is it possible to import a new image when the app is running, so I cannot change the displayed image this way. Similarly I thought about overwriting the old image with a new one, but even if the path doesn't change, I don't know how to update the image.
I'm new to web programming and I'm wondering if I'm going at this the wrong way in terms of displaying something dynamically.
Here is a code sample:
import React from "react";
import ReactDOM from "react-dom";
import image from "./graph.png";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
img: image,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
event.preventDefault();
console.log("A new image with path ./newgraph.png is generated somehow");
console.log("The next line doesnt work: ");
import image from "./newgraph.png";
this.setState({ img: image });
}
render() {
return (
<div>
<button onClick={this.handleClick}> Submit </button>
<img src={this.state.img} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Thank you !
When you import image from "./newgraph.png" you are importing the actual data that comprises the image, not the src link to the image. In this case, you don't want to import the image at all, you want something closer to:
handleClick(event) {
event.preventDefault();
console.log("A new image with path ./newgraph.png is generated somehow");
console.log("The next line doesnt work: ");
this.setState({ img: "path/to/your/image.png });
}