ItsTheJourney
ItsTheJourney

Reputation: 23

Changing image source dynamically for carousel

I am starting off learning React and building a simple picture carousel. I have 3 images I am pulling from Github in a const array. The requirement would be to have a forward and back button to cycle through the images.
Upon app start, the 1st image shows up correctly. The button increments a counter correctly (I have console logs confirming that).
But the <img> does not refresh/reload loading the next image from the array based on the revised counter variable.

At the moment I only have the forward button functionality implemented.

const photoList = [
  "https://avatars0.githubusercontent.com/u/810438?v=4",
  "https://avatars2.githubusercontent.com/u/6820?v=4",
  "https://avatars2.githubusercontent.com/u/63648?v=4"
];

//Component for the Forward button

function ForwardButton(props) {
  console.log("Forward Button clicked");
  const handleClick = () => props.OnClick(props.increment);
  return <button onClick={handleClick}> --> </button>;
}

//Component for the Back button

function BackButton() {
  return <button className="BackButton"> {"<--"} </button>;
}

//Main component with other components nested

function App() {
  const state = {
    profiles: photoList
  };

  let count = 0;

  const [counter, setCounter] = useState(0);
  const IncrementCounter = incrementValue => {
    setCounter((count = counter + incrementValue));
    console.log(count);
  };
  return (
    <div className="App">
      <header> Picture Carousal</header>
      <img className="Image" src={state.profiles[count]} />
      <BackButton />
      <ForwardButton OnClick={IncrementCounter} increment={1} />
    </div>
  );
}

ReactDOM.render(<App />, mountNode);

I would like to use this very simple implementation and try to figure out how to make <img> refresh with new image. Hopefully this is an easy fix.

Upvotes: 0

Views: 119

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

The count being defined inside the App component gets reset on each re-render.

You will have to either define it outside the component (but that could create some problems if you want two App components at the same time).

Or you could use the counter directly, which is the whole point of using state. (also use modulo with the length of your array to limit the counter to only values matching the images)

const IncrementCounter = incrementValue => {
  setCounter((counter + incrementValue) % photoList.length);
};

Demo at https://codesandbox.io/s/nostalgic-browser-qfudx

Upvotes: 1

Related Questions