How can I implement a button that dynamically updates the id parameter in slide.filter in order to display various elements from an array in a REACT application?

I am attempting to create a text carousel that displays data from an array one at a time. I have stored the data in an array and now I want to implement a button that allows me to navigate through the array entries. However, I am facing issues finding a solution for this. Can anyone help?

.jsx

import React from 'react'
import './CambioMesPeriodo.css';
import { useState } from "react";

export default function CambioMesPeriodo() {
const slidesArray = [
{id: 1,
Sup: 'Texto Superior 1',
Inf: 'Texto Inferior 1'},

{id: 2,
Sup: 'Texto Superior 2',
Inf: 'Texto Inferior 2'},

{id: 3,
Sup: 'Texto Superior 3',
Inf: 'Texto Inferior 3'} ]

const [slide] = useState(slidesArray);

var array = 1;

const values = slidesArray.map(object => object.id)

let validSlide = slide.filter(slides => slides.id === (values,array))



return (

  <div className="slideshow-container">  
      <div>
      <p> {validSlide[0].Sup} </p>
      <p> {validSlide[0].Inf} </p>
      </div>
    
     {/*  <div> {values.map(name => <h2>{name}</h2>)} </div> */}

      <button >Adelante</button>



   </div>
    )}

.css

    /* Slideshow container */
   .slideshow-container {
   position: relative;
   background: #898989;
   border-radius: 10px;
   width: 310px;
   height: 65px;}

Displayed on Web: here is the image description

Answer №1

Outlined below is a potential method to accomplish the specified goal.

Code Extract

const {
  useState
} = React;

function ChangeMonthPeriod() {
  const slidesArray = [{
      id: 1,
      Top: 'Top Text 1',
      Bottom: 'Bottom Text 1'
    },

    {
      id: 2,
      Top: 'Top Text 2',
      Bottom: 'Bottom Text 2'
    },

    {
      id: 3,
      Top: 'Top Text 3',
      Bottom: 'Bottom Text 3'
    }
  ]

  const [slide] = useState(slidesArray);
  
  const [idx, setIdx] = useState(0); // initialized "idx" as 0
  // "idx" is used to index the "validSlide" array
  
  var array = 1;
  const values = slidesArray.map(object => object.id)
  // commented due to uncertain function & hence uncertainty
  // let validSlide = slide.filter(slides => slides.id === (values, array))
  
  // for now, consider "validSlide" same as "slide"
  let validSlide = slide; 

  return (
    <div className="slideshow-container">  
      <div>
        <p> {validSlide[idx].Top} </p>
        <p> {validSlide[idx].Bottom} </p>
      </div>
      <button
        onClick={           // update the "idx" to next slide or back to zero (if at end)
          () => setIdx(
            prev => (
              (prev + 1) % validSlide.length
            )
          )
        }
      >
        Forward
      </button>
     </div>
  )
};

ReactDOM.render(
  <div>
    DEMO
    <ChangeMonthPeriod />
  </div>,
  document.getElementById("rd")
);
.slideshow-container {
  position: relative;
  background: #898989;
  border-radius: 10px;
  width: 310px;
  height: 65px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

Description

Clarifying notes included in the provided code snippet above.

Note: If you wish to contribute to the Stack Overflow community,

Please take a moment to read: What to do when my question is answered Thank you !

Answer №2

How about starting with a simple code snippet in the .js file like this:

import React, { useState } from 'react';
// Use your preferred library to add button functionality
import { Button } from '@mantine/core';


export default function ChangeMonthPeriod() {
    const slidesArray = [
    {
        id: 1,
        Sup: 'Top Text 1',
        Inf: 'Bottom Text 1'
    },
    {
        id: 2,
        Sup: 'Top Text 2',
        Inf: 'Bottom Text 2'
    },
    {
        id: 3,
        Sup: 'Top Text 3',
        Inf: 'Bottom Text 3'
    }]

    const [slideId, setSlideId] = useState(0);

    return(
        <div>
            <p>
                {slidesArray[slideId].Sup}
            </p>
            <p>
                {slidesArray[slideId].Inf}
            </p>
            <Button value={slideId} onClick={() => setSlideId(previousValue => previousValue + 1)}></Button>
        </div>
    );
};

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

Locating the Searchbox on Google Maps with the angular-google-maps library

I am currently working on positioning the Google Maps searchbox variable in a way that allows it to stay fixed under markers as they are listed. I am utilizing the Angular Google Maps library for this purpose, which provides a directive known as <ui-g ...

Having trouble with the error "Cannot GET /" in your Angular2 and Express

I've been working on customizing this GitHub example application to utilize Express instead of KOA. When I enter gulp serve in the CentOS 7 terminal, the app launches successfully. However, upon typing http : // localhost : 8080 in the browser, a 404 ...

Is there a way to customize the look of the close button on a Bootstrap 5 search box?

I am currently in the process of designing a blog template using Bootstrap 5. While working on creating the search box, I encountered a minor issue. The code snippet below has provided me with a small close button: .input-group-append .btn { border-bot ...

typescript unable to use module as variable in import statement

Having trouble importing a variable from another file in TypeScript and assigning an alias name. I keep getting an error saying the alias name is not defined. For example: import { headerItems as TestHeader } from './headers'; Typescript versi ...

Connecting with a php anchor and hash symbol in a website URL

Looking to include a PHP anchor along with a hash anchor in an HTML link. <?php echo '<a href="test.php?page='.$i.'#hash">'.$i.'</a>'; ?> The PHP code successfully echoes the link, but upon clicking it, th ...

Tips for handling date type input to accommodate both JSON format and date format within AngularJS

I have a RESTful service that both produces and consumes JSON objects. { firstName: "Alex", lastName: "Ross", studentGroup: { groupId: 1, groupName: "java 15-1" }, admissionDate: "2015-03-25", status: { statusId: 3, statusName: "expelled" }, term: { termI ...

How to Trigger a Google Apps Script Function from an HTML Page

I lead a sports team and created a website for it. I'm interested in adding a button to an admin page that allows me to send a quick email to all team members at once. The message would typically read: "Important update - please check the website for ...

Script to identify compatibility with Bootstrap 4 in Javascript

As I work on developing a website utilizing Bootstrap 4 for its UI design, I have encountered the issue that Bootstrap 4 does not support IE 8 and certain older versions of browsers. In order to address this, I am looking to implement an error page that w ...

Error message: UnhandledPromiseRejectionWarning in (Node.js, Express.js, MongoDB) - TypeError occurs when trying to access an undefined 'username' property

I'm struggling to fetch and print the post's author from mongodb using client-side code. Unfortunately, my current code is throwing an error. It is a fullstack javascript code and despite my efforts in searching for a solution, I couldn't fi ...

Ways to eliminate the gap between two columns within a row, where the third column begins directly after the second one, causing a significant gap

I am facing an issue with the layout of my columns within a row. I have two columns inside the row and another column outside of the first row. The problem is that the third column (col-3) starts at the end of col-1, causing a gap between col-1 and col-3 ...

Guide on how to modify the color of a single row within a table with just a click

My table structure is as follows: <table> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> </tr> <tr> ...

How can we use vanilla JavaScript to implement an image zoom effect on mouse movement?

I'm attempting to implement an onmousemove event within an image that displays a zoomed image on the right side. Issue: When I move my mouse inside the image, the black box and zoomed image flicker. The zoomed image does not align correctly in the b ...

How can Python be used to change the positions of characters using their indices?

Two arrays, encryted_message = [] and index_shuffle = [], are used in this encryption process. The encryted_message = [] array takes the user input and splits the words into individual characters, while the index_shuffle = [] array keeps track of the index ...

Showing a series of words individually on separate lines using the IN and OUT flags

I wrote a program that is capable of storing multiple lines entered by the user and then checking for new words to print on new lines. Here's the code I used: #include<stdio.h> #define IN 1 //inside a word #define OUT 0 //outside a word in ...

Implement a top bar above the navigation bar using Bootstrap

Attempting to construct a webpage from scratch for the first time, without relying on a template. I aim to implement a fixed top bar above the navigation bar. Referencing this example: This is my current code: window.onscroll = function() { scrollFun ...

Browser disregards backslashes in the content of pseudo elements

I have been struggling with a simple issue for quite some time now, and I seem to be out of ideas. The problem lies in the styling of a CSS pseudo-element before, which is defined as follows: #fPhone::before{ color: #78be20; content: "\e622" ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Node.js throws an error stating that it is unable to read the property 'p_nome' because it is undefined

Hello, I am a newcomer to the world of react and node.js, and I have encountered a problem. On a webpage, I have a table where I am supposed to display data related to a trip. The columns (Locales Id, name, date, time) are part of the travel_order model, ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

The values from the form fields are not being properly transferred into the JSON object

Check out my JSFiddle here: https://jsfiddle.net/inchrvndr/7pwh9p8g/ When you click the "+" button, the bordered form elements are getting cloned. All the values of the cloned form elements are being passed into JSON data except for the parent element fr ...