Showing a unique image and its corresponding title in a React carousel component when the page loads and when a button is clicked

I am currently developing a slideshow feature in a React component that will display a random image along with its associated title either when the page loads or when the user clicks on the next button within the slideshow. In order to achieve this, I have created an array of objects containing image URLs and titles. However, I am struggling to write the necessary function that will select a random image from the array and then correctly display both the image and its title. Here is my progress so far, although I am unsure of how to proceed further. Any assistance would be greatly appreciated!

import React, { Component } from "react";
import "../styles/slideshow.css";

export default class Slideshow extends Component {
  images = [
    {
      headline: "Title 1",
      link:
        "www.example1.com"
    },
    {
      headline: "Title 2",
      link:
        "www.example2.com"
    },
    {
      headline: "Title 3",
      link:
        "www.example3.com"
    }
  ];

  displayRandomImage = () => {
    let index = Math.floor(Math.random() * 3);
  };

  render() {
    return (
      <div>
        <div id="slideshow" class="carousel slide" data-ride="carousel">
          <div class="carousel-inner">
            <div class="carousel-item active">
              <img class="d-block" src={} alt="First slide" />
            </div>
          </div>
          <a
            class="carousel-control-prev"
            href="#carouselExampleControls"
            role="button"
            data-slide="prev"
          >
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
          </a>
          <a
            class="carousel-control-next"
            href="#carouselExampleControls"
            role="button"
            data-slide="next"
          >
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
          </a>
        </div>
      </div>
    );
  }
}

Answer №1

import React, { Component } from "react";
import "../styles/slideshow.css";

export default class RandomSlideshow extends Component {
  constructor() {
    this.state = {
      imgIndex: null
    };
  }

  images = [
    {
      headline: "Title A",
      link: "www.exampleA.com"
    },
    {
      headline: "Title B",
      link: "www.exampleB.com"
    },
    {
      headline: "Title C",
      link: "www.exampleC.com"
    }
  ];

  componentWillMount() {
    this.showRandomImage();
  }

  showRandomImage = () => {
    this.setState({
      imgIndex: Math.floor(Math.random() * 3)
    });
  };

  render() {
    return (
      <div>
        <div id="random-slideshow" className="carousel slide" data-ride="carousel">
          <div className="carousel-inner">
            <div className="carousel-item active">
                <div className='carousel-image_title'>{this.images[imgIndex].headline}</div>
              <img
                className="d-block"
                src={this.images[imgIndex].link}
                alt="First slide"
              />
            </div>
          </div>
          <a
            className="carousel-control-prev"
            href="#random-carouselControls"
            role="button"
            data-slide="prev"
          >
            <span className="carousel-control-prev-icon" aria-hidden="true"></span>
            <span className="sr-only">Previous</span>
          </a>
          <a
            className="carousel-control-next"
            href="#random-carouselControls"
            role="button"
            data-slide="next"
          >
            <span className="carousel-control-next-icon" aria-hidden="true"></span>
            <span className="sr-only">Next</span>
          </a>
        </div>
      </div>
    );
  }
}

    enter code here

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

CORS - Preflight request response fails access control verification

I've been attempting to send a GET request to a server with the same domain as my local host, but I keep encountering the following error: The preflight request response fails the access control check: The requested resource does not have an ' ...

Why Are My JavaScript GET Request Parameters Displaying as Strings Rather Than Numbers?

Currently, I am in the process of developing a REST API where one of the defined routes looks like this: router.get("/objects/:id?/:val1?/:val2?", getObject); Specifically, my request from Postman appears as follows: http://localhost:8000/objects?val1= ...

Explore the search bar with functional filtering for JSON items

I'm currently working on creating a dynamic filter bar integrated with a search functionality. My data is stored in JSON format, including details such as artist name, title, source, and more. Despite successfully retrieving results through console.lo ...

Preventing opening while closed through the OnClick event

I have the following OnClick function: const [open, setOpen] = useState(true); and onClick={() => setOpen(!open != true)} The goal is to "close when open" and "remain closed if already closed". The current code achieves the second part but not the fir ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Utilizing Javascript Conditional for Substitution

Currently, I have a JavaScript function that replaces all links with registration messages: <script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { ...

Caution: flattenKids(): Two children with identical keys, `false`, have been detected in the ReactJS environment

Currently, I am working on creating a clickable list where each item redirects me to another page upon clicking. Below is the render method: render() { const quesItems = this.state.questions.map((question, i) => { return ( <li key={this.prop ...

Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file. While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it ch ...

Running Javascript code after rendering a HandleBars template in Node/Express

I have a Node.js application where I am trying to load data into a jQuery datatable after the data has been fetched. Currently, I am able to populate the table with the data, but I am facing issues initializing the datatable. Here is how I render the temp ...

Dealing with a Bootstrap 4 fixed-top navbar issue: Uncovering the mystery behind the white space

I'm encountering an issue with the navbar that is causing a white space: see screenshot. Here is the HTML code I am using: <div class="header"> <div class="overlay"></div> <nav class="navbar fi ...

A guide on verifying a phone number using just one character

I am looking to validate a phone number with only one character being allowed. For example, the format should be XXX-XXXXXXX where "-" is the only allowed character. Below is my validation function: function validatePhoneNumber() { if(addform.staff_m ...

My lists are not being styled by Embedded and Internal CSS

I want the ingredients list to be styled in green, equipment list in red, and method list in blue using different CSS techniques. My external works fine for changing the color to red, but my internal styles don't seem to apply to the other lists. < ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Using the concept of a while loop in PHP, you can easily retrieve the values of Radio Buttons on one page and

Is there a way to retrieve and store radio button values in a MySQL database using PHP looping concepts? $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_row($result)) { ?> ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

Can someone explain the meaning and syntax of this code in a clear way

I recently encountered this syntax in a tutorial and I'm unsure if it's ES6. It was part of a reduce function. Can someone provide a clear explanation of what is happening inside these parentheses? {...curr, ...acc} Here is the full code snippe ...

Using React Autosuggest as a Functional Component by Importing it from a Separate JSX File

Currently, I am working on a simple web frontend with React using react-autosuggest to search for a specified user from a list. My goal is to utilize Autosuggest to provide suggestions as users type in the query in the search field, based on the usernames ...

Using Node.js, Express, and Socket.IO to establish real-time communication between two static client pages

I'm in the process of creating a remote control for a gallery using nodejs, express, and socket.io. Here's the project structure: /index.js /public/screen.html /screen.js /remote.html /remote.js The goal is to display a gallery of ima ...