Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click?

For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow should go back to the previous image.

Below is my code snippet:

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'm encountering a persistent error while testing this function. Any guidance or advice would be greatly appreciated.

Answer №1

Make sure to keep track of the variable i in your state, as it will allow you to trigger a re-render of the page when the state changes using setState. Additionally, ensure that the source variable is set to 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>
        )
    }
}

Answer №2

Try using setState({'i':i}) to update your state. By calling setState, the component will reRender and this solution should resolve your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Tailwind CSS to center a NexJS <Image /> component within a modal

In an effort to style my MapBoxGL popup content, I am working on aligning the text above the image to the left and centering the image below within the popup. As shown in the image below, this is currently proving to be a challenge as I transition from usi ...

Help me understand how to display the data in a JSON array

{ "entries": [ { "id": 23931763, "url": "http://www.dailymile.com/entries/23931763", "at": "2013-07-15T21:05:39Z", "message": "I ran 3 miles and walked 2 miles today.", "comments": [], "likes": [], ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

How to position preloader at the center in materializeCSS

Given this situation: I attempted to implement this Preloader with position:fixed and centered. My approach was as follows: .loader { position:fixed; top:50%; left:50%; -webkit-transform:translate(-50%,-50%); } <link rel="stylesheet" href="h ...

Creating a responsive canvas and image container in fabric.js involves adjusting the layout and size of the

I am working with fabric.js and canvas to dynamically add an image from a URL. I would like to make the canvas responsive based on the resolution. How can this be achieved? Here is my current code: <canvas id="panel" width="700" height="350"></ ...

Employ linq for querying through an array of strings

Just starting out with linq and trying to grasp some basic functionality. I have a string that needs to be split into an array, and then I want to search for specific values within that array. This is what I have so far: string input = "a1,b2,c3,d4"; var ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

Vue parent component not receiving events properly

Referring to these sources: Forum Post Stack Overflow Question In my project, I am utilizing: CodeSandbox Example The setup involves the parent component listening for events emitted by a child component: mounted() { this.$on("edit-category& ...

Material UI DateTimePicker Displaying Incorrectly

I am implementing a new Material UI date time picker on page load by setting the open prop. <Grid item xs={6} className={styles.CampaignDates_calendar_right}> <MuiPickersUtilsProvider utils={DateFnsUtils} className={styles.CampaignDates_calendar ...

React Router - Implementing a <Redirect> element rather than a list of child components

Here is the code snippet I am working with: import { Redirect } from 'react-router-dom'; import QPContent from '../QPContent'; class AnswerContainer extends Component { constructor(props) { super(props); this.state = { ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

What is the best way to ensure the header spans the entire width of a webpage using the display: flex; property and flex-direction: column styling within the body element

Click here for the CSS code snippet Hello everyone, this is my very first query on Stack Overflow. I know it might be a simple question but it's my first time posting here so kindly bear with me. Below is the CSS code snippet provided: *{ ...

Ensuring form field accuracy through server-side validation using Ajax - Mastering the art of Ajax

I am in need of implementing Ajax to validate my form fields, currently I have a javascript validation set up. Is it possible to reuse my existing javascript code and integrate Ajax for form validation? HTML Form <form method="post" action="ajax/valid ...

MUI: (Autocomplete) The input given for Autocomplete is not valid

While attempting to load data into an MUI Autocomplete, I encountered this message in the console. React-hook-form and yup are being used for form validation. Image displaying the warning To showcase my issue, I have set up a CodeSandbox. In this example, ...

What is the best way to deactivate buttons with AngularJS?

I have a situation where I need to disable the save button in one function and permanently disable both the save as draft and save buttons in another function using AngularJS. How can I accomplish this task with the disable functionality in AngularJS? Her ...

Issue with mobile flipcard: Initial tap is unresponsive

Currently debugging the mobile version of a site built with Next.js. Encountering an issue where the first flip-card tapped on mobile refuses to flip properly. Instead, it selects the text on the opposite side of the card when tapped multiple times. The ...

Utilize React Material UI Slider to dynamically adjust Border Radius in your web design

Utilizing React Material UI's components like the slider and button is essential for this project. The main objective is to dynamically change the border radius of the button using the value obtained from the slider. However, there seems to be a chall ...

Strange glitch in the rendering of rectangles on HTML5 canvas?

While experimenting with pre-rendering sprites using HTML5 canvas, I encountered some strange behavior that appears to be a rendering bug. The issue can be seen in the following minimal example: var CT = document.getElementById("myCanvas").getContext("2 ...