Im trying to change the img src getting the src from and array based on the direction of arrow that is clicked in react.js.
So for example I have an array when a user clicks on the right arrow it will change the img src forward and if she clicks backs it will go back the prev image
here is my code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/index';
import { Link } from 'react-router';
var i = 0;
var blogPostImages = ['./img/placeholder.jpg', './img/placeholderB.jpg', './img/placeholderC.png'];
export default class HomePage extends Component {
changeBlogPicForwards() {
if (i == blogPostImages.length - 1) {
i = 0;
} else {
i = i + 1;
}
let blogPostImages = blogPostImages[i];
}
changeBlogPicBackwards() {
if (i == 0) {
i = blogPostImages.length - 1;
} else {
i = i - 1;
}
}
render() {
var blogCurrentPic = this.state.blogPostImages[i];
return (
<div>
<div className="top-section-actions">
<div className="image-holder">
<img className="blog-pictures" src={blogPostImages}/>
</div>
<div className="blog-name">
<div className="left-arrow-action arrow-icons">
<i onClick={(e) => this.changeBlogPicForwards(e)} className="fa fa-arrow-circle-o-left fa-2x" aria-hidden="true"></i>
</div>
<div className="right-arrow-action arrow-icons">
<i onClick={(e) => this.changeBlogPicBackwards(e)} className="fa fa-arrow-circle-o-right fa-2x" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
)
}
}
I keep getting an error any help will be much appreciated.
You need to maintain i
in the state so that you can signal react to re-render the page when the state changes using setState
. Also, the src should be blogCurrentPic
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/index';
import { Link } from 'react-router';
export default class HomePage extends Component {
constructor() {
this.state = { index : 0 };
this.blogPostImages = ['./img/placeholder.jpg', './img/placeholderB.jpg', './img/placeholderC.png'];
}
changeBlogPicForwards() {
let i = this.state.index;
if (i == this.blogPostImages.length - 1) {
i = 0;
} else {
i = i + 1;
}
this.setState({index: i});
}
changeBlogPicBackwards() {
let i = this.state.index;
if (i == 0) {
i = this.blogPostImages.length - 1;
} else {
i = i - 1;
}
this.setState({index: i});
}
render() {
var blogCurrentPic = this.blogPostImages[this.state.index];
return (
<div>
<div className="top-section-actions">
<div className="image-holder">
<img className="blog-pictures" src={blogCurrentPic}/>
</div>
<div className="blog-name">
<div className="left-arrow-action arrow-icons">
<i onClick={(e) => this.changeBlogPicForwards(e)} className="fa fa-arrow-circle-o-left fa-2x" aria-hidden="true"></i>
</div>
<div className="right-arrow-action arrow-icons">
<i onClick={(e) => this.changeBlogPicBackwards(e)} className="fa fa-arrow-circle-o-right fa-2x" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
)
}
}