Reputation: 1324
Depending on which link is clicked, I would like to update the img src in the MapImage
Component
import React from 'react'
import NavLink from './NavLink'
var MapImage = React.createClass({
render: function() {
return <img src={'./img/' + this.props.img + '.png'} />
}
});
export default React.createClass({
getInitialState: function () {
return { img: '1' }
},
loadImage: function () {
this.setState({
img: this.props.img
});
},
render() {
return (
<div>
<h2>Maps</h2>
<ul>
<li><NavLink onClick={this.loadImage} to="/maps/firstfloor" img='1'>1st Floor</NavLink></li>
<li><NavLink onClick={this.loadImage} to="/maps/secondfloor" img='2'>2nd Floor</NavLink></li>
<li><NavLink onClick={this.loadImage} to="/maps/thirdfloor" img='3' >3rd Floor</NavLink></li>
</ul>
{this.props.children}
<MapImage img={this.state.img} />
</div>
)
}
})
The image src is updated to ./img/undefined.png
Upvotes: 0
Views: 1360
Reputation: 17064
You don't have that image value in the props when you're doing:
this.setState({
img: this.props.img
});
Try to pass a parameter to the loadImage
function, and use it in the setState
:
// in JSX
onClick={ function () { this.loadImage(1); } }
// function
loadImage: function (img) {
this.setState({
img: img
});
}
For each NavLink image.
In general, I'd recommend having an array and iterating over it, like:
var images = [{
value: 'firstfloor',
text: '1st Floor'
},
{ ... // other objects }]
And then iterate like this (or change values depending on your logic):
{
images.map((image, index) => {
return (
<li>
<NavLink
onClick={ function () { this.loadImage(index); } }
to={ '/maps/' + image.value }
img={ index }>
{ image.text }
</NavLink>
</li>
);
});
}
Upvotes: 2