Reputation: 709
I have an API call that retrieves an array of objects that looks like this {id: 12313, isComplete: true}
changeImage(isComplete: string) {
let image = document.getElementById("icon-status") as HTMLImageElement
if(isComplete) {
return image.src = '../ClientApp/images/Green.png'
}
return image.src = "../ClientApp/images/Grey.png";
}
Basically set image.src = "green" if isComplete = true, else set image.src = "grey"
my HTML looks like this <img src={this.changeImage(task.isComplete)} width="22" alt="" className="icon" id="icon-status"/>
At the moment I'm getting TypeError: Cannot set property 'src' of null..
Any ideas?
Upvotes: 2
Views: 1494
Reputation: 1
const [image, setImage] = useState()
useEffect(() => {
if (isComplete) {
setImage(require('../ClientApp/images/Green.png'))
} else {
setImage(require('../ClientApp/images/Gray.png')
}
}, [image])
<img
src={image}
width="22"
alt=""
className="icon"
id="icon-status"
/>
Upvotes: 0
Reputation: 112807
Instead of trying to manipulate the img element in the DOM, you could use task.isComplete
with the ternary operator to give the img element the correct src
.
<img
src={
task.isComplete
? "../ClientApp/images/Green.png"
: "../ClientApp/images/Grey.png"
}
width="22"
alt=""
className="icon"
id="icon-status"
/>
Upvotes: 2