Reputation: 43
Alright hey guys. Trying to get this clock functioning with the pictures. I have more than just the one but if I can get the one figured out I can handle the others. After much searching I found out you can't use string interpolation within an attribute but I kept it there to show I tried. The second one I think "should work" and it shows the variable i'm trying or pic0, pic1 and so on but it's a string not the actual module i'm importing at the top (in the actual app I have them all imported but cut them down for brevity on the question. Any assistance?? I'm bashing my head what is causing this issue
import React, { Component } from 'react';
import './App.css';
import './bootstrap-3.3.7-dist/css/bootstrap.min.css';
import pic0 from './0.png';
export default class Clock extends Component {
constructor(props) {
super(props);
this.incrementTime = this.incrementTime.bind(this);
this.dayInWords = this.dayInWords.bind(this);
this.state = {
clock: new Date(),
day: (new Date()).getDay(),
hours0: 0,
minutes0: 0,
seconds0: 0,
hours1: 0,
minutes1: 0,
seconds1: 0
}
}
componentWillMount() {
let intervalTimer = setInterval(this.incrementTime, 1000);
}
componentWillUnmount() {
clearInterval(this.state.intervalTimer);
}
incrementTime() {
this.setState(currentState => {
return {
clock: new Date(),
seconds1: ((new Date()).getSeconds())%10
};
});
}
render() {
return(
<div className='panel-body imgContainer'>
<img src={pic0} alt='the digit 0' />
<p>Know this one doesnt work but kept here to show I tried it</p>
<img src={`pic${this.state.seconds1}`} alt='seconds1' />
<p>I think this should work and the src is what I want as the variable that im importing at the top but its just a string not the variable.</p>
<img src={'pic' + this.state.seconds1} alt='seconds1' />
<p>This is the end goal im trying to accomplish but im trying to see if it can be done using this.state.seconds so its kind of "dynamic" and the source changes every second thus changing the image</p>
<img src={pic0} alt='seconds1' />
</div>
);
}
}
this is what i'm seeing it's the image not showing the src is the "variable" im importing at the top but it's not actually calling that variable/module sorry if my terminology is wrong i'm clearly pretty new at this.
Thanks for all the assistance!!!!
Upvotes: 0
Views: 87
Reputation: 17064
Although this was clarified in the comments, for future visitors of this post - you need to reference the imported image directly:
import pic from './myImage';
// works
<img src={ pic } />
It can be placed in the state, or some other variable, but can't be accessed via a string with the same name:
// Doesn't work
<img pic={ 'pic' } />
Upvotes: 1