React custom slider component is failing to meet expectations

I've been working on enhancing my React skills and building my portfolio. Instead of using a library, I opted to create a custom slider using the code below:


    const ProjectWrapper = styled.div`
      .container {
        transform: translateX(-${(props) => props.activeIndex * 200}px);
        transition: transform 0.3s;
        display: flex;
        flex-direction: column;
        margin: 20px;
        border: 1px solid gray;
        border-radius: 5px;
        padding: 20px;
        text-align: justify;
        color: white;
        text-decoration: none;
        height: 450px;
      }
    `;

    export default function Portfolio() {

      const [activeIndex, setActiveIndex] = useState(0);

      const updateIndex = (newIndex) => {
        if (newIndex < 0) {
          newIndex = projects.count - 1;
        } else if (newIndex >= projects.count) {
          newIndex = 0;
        }
        setActiveIndex(newIndex);
      };

      return (
        <div>
          <Arrow>
            <ProjectWrapper activeIndex={activeIndex}>
              {projects.map((el, idx) => {
                return (
                  <a key={idx} className="container" href={el.url}>
                    <div>
                      <div className="img">
                        <img src={el.image} alt={el.title} />
                      </div>
                      <div className="row">
                        <h3 className="title">
                          {el.title}
                          <a target="_blank" href={el.github}>
                            {el.github === "" ? (
                              ""
                            ) : (
                              <i className="fa-brands fa-github fa-lg"></i>
                            )}
                          </a>
                        </h3>
                        <div className="desc">
                          <p>{el.description}</p>
                        </div>
                        <p>
                          <b>Technologies:</b> {el.resources}
                        </p>
                      </div>
                    </div>
                  </a>
                );
              })}
            </ProjectWrapper>

            <button
              onClick={() => {
                updateIndex(activeIndex - 1);
              }}
            >
              {" "}
              <i class="fa-solid fa-angle-left"></i>
            </button>
            <button
              onClick={() => {
                updateIndex(activeIndex + 1);
              }}
            >
              <i class="fa-solid fa-angle-right"></i>
            </button>
          </Arrow>
        </div>
      );
    }
  

Everything seems to be working well except for a couple of issues:

  1. Once the last card is displayed, I want the next arrow to be disabled.
  2. After navigating to the next card and then going back to the beginning, the next arrow is not clickable anymore. It only works again after refreshing the page.

Does anyone have any suggestions on how to improve my code to address these issues?

Answer №1

If you want to deactivate the "Next" button, simply include a conditional disabled attribute. In this scenario, the button will be disabled when the state matches the total number of projects:

<button
    onClick={() => {
      updateIndex(activeIndex + 1);
    }}
    disabled={activeIndex === (projects.count - 1)}
/>

Regarding your second issue, your current function resets the index to 0 once you reach the final slide. This means that when you are on slide 5/5, the index goes back to 0:

else if (newIndex >= projects.count) {
  newIndex = 0;
}

This can cause confusion in the logic, so my suggestion would be to eliminate updateIndex() and modify your buttons in the following manner:

<button
      onClick={() => setActiveIndex((prevIndex) => prevIndex + 1)}
    >
      <i class="fa-solid fa-angle-right"></i>
    </button>

Alternatively, you can use -1 for the back button.

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

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Is it necessary to overlook Java Script when conducting load testing on my website?

We are in the process of developing a robust web application that needs to be able to handle a significant amount of traffic. I have been conducting load tests on a HP (Proliant DL 380) server with two 3.6GHz Xeon CPUs and 16GB of RAM. To perform these tes ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Exploring the Mystery of why Three.js Fails to Apply Textures to Objects

I'm attempting to add a texture to an object with the following code: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; h ...

Consistent CSS alignment across all browsers

I have designed a four-digit counter that needs to be displayed in the bottom right corner of the page. Each digit is represented by a block image as a background. It is functioning properly in Chrome, but there are compatibility issues with IE7+ and Firef ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

What is the process for establishing a connection between two sets of data?

I am working with two mongoose models: user.js and note.js, which correspond to the collections notes and users. I want users to be able to save their notes, but I'm unsure how to create relationships between these collections. Ideally, I would like t ...

Next Value in Array Following Selected One

Apologies for the repetition, but despite my attempts, I haven't been able to find a solution that works for me. When a user clicks on an element, I need to retrieve the following information: The ID of the selected element An array containing all v ...

The expected functionalities of jQuery animation are not being achieved

Here is my jQuery script: <script> $(document).ready(function () { $("#tt").mouseover(function () { $("#aa").animate({ padding: "5px 0 5px 100px", backgroundColor: "#7EEFF7", }); }); $("#tt").mouseout(function () { $( ...

Learn how to implement console-like Tail functionality in a web application using the MaterialUI TextField component as the console interface

Issue with Component: Scroll not Updating as new content is added to TextField: https://i.sstatic.net/lgOtn.png I am currently in the process of developing a live console feature within a React application and I wanted to utilize MaterialUI's TextFie ...

Tips on aligning nodes in highcharts

I've been attempting to align nodes, but I'm having trouble finding any options on how to do it. Here is my current code: Highcharts.chart('container', { chart: { type: 'networkgraph', plotBorderWidth: 1 }, title: { ...

Alert: The flattening operation is not a recognized function. Proceed with --force option to proceed

I've encountered a strange error with Grunt. After some time in our CI system, the task grunt assemble:site starts to fail and outputs the following warning: Running "assemble:site" (assemble) task Warning: flatten is not a function Use --force to co ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

Align numbers vertically inside scrollbar center

I have created a program where you can input a number, and it will count from 0 to the specified number. Currently, the numbers are aligned horizontally up to 12 before starting on a new line. However, I would like the numbers to be arranged vertically fr ...

What steps can be taken to allow for the addition of multiple slick sliders using the same class on a single page?

When using the admin panel, the user has the ability to add multiple sliders to the page. How can all sliders with the same class be initialized? Is there a way to ensure that the control buttons for each slider are applied individually, instead of just f ...

Error occurred during React npm module build due to failure in ./node_modules/babel-loader/lib/index.js

While setting up my React environment, I encountered two errors when running npm start in the command prompt. The first error states "module build failed (from ./node_modules/babel-loader/lib/index.js)" and the second error is "error plugin/preset files a ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...