Reputation: 4054
I am using react router v4 for routing. Link is applied in the image. When that image is clicked(if it is active), i want to change that image.
Here is the code to show the concept of what i want
class PrivateServiceType extends Component {
render() {
console.log('context', this.context.router);
let image = isActive ?
<img src={IconHouseSelected} alt="apartamentos" className="img-responsive" /> :
<img src={IconHouseNotSelected} alt="apartamentos" className="img-responsive" />
return (
<div className="row text-center">
<div className="col-xs-12 col-sm-12 col-md-4 serviceImg">
<Link to="/apartamentos">
{image}
<h4>APARTAMENTOS</h4>
</Link>
</div>
)
}
PrivateServiceType.contextTypes = {
router: React.PropTypes.object
}
Upvotes: 0
Views: 3342
Reputation: 2155
Store currentUrl
as a state object and assign that as the src
of the img
. Put a onClick
handler on the img to toggle the currentUrl
.
class PrivateServiceType extends Component {
constructor(){
super();
this.state = {
iconhouseUrl = 'notselected.png'
}
this.toggleIcon = this.toggleIcon.bind(this);
}
render() {
console.log('context', this.context.router);
return (
<div className="row text-center">
<div className="col-xs-12 col-sm-12 col-md-4 serviceImg">
<Link to="/apartamentos">
<img src={this.state.iconhouseUrl} alt="apartamentos" className="img-responsive" onClick={this.toggleIcon}/>
<h4>APARTAMENTOS</h4>
</Link>
</div>
)
}
toggleIcon(){
if(this.state.iconhouseUrl === 'notselected.png')
this.setState({iconhouseUrl:'selected.png'})
else
this.setState({iconhouseUrl:'notselected.png'})
}
}
PrivateServiceType.contextTypes = {
router: React.PropTypes.object
}
The iconhouseUrl
state variable holds the url and the toggleIcon
function handles the change which is bound to the onClick
handler of the img
In accordance with your comment here is a route sensitive way
<Link to="/apartamentos">
<img src={(location.pathname === '/apartamentos' )?'houseselected.png':'houseunselected.png'}
alt="apartamentos" className="img-responsive"/>
<h4>APARTAMENTOS</h4>
</Link>
What this does is compare the current path (contained in location.pathname
) with the condition and accordingly sets the icon.
Upvotes: 2