Sliding the content in React

My current project involves creating a content slider in React. While I have made some progress, I am facing a challenge in making the content move horizontally instead of vertically. Currently, all the items are stacked on top of each other, preventing them from functioning as a horizontal slider. I initially attempted to use flexbox to align the items next to each other, but I ran into issues with moving them left or right in the CSS.

My approach so far has been setting the top of the inner div (which houses the items) to a calculated number of pixels to display the next "slide". However, I have been struggling to get the items to line up next to each other and change the left/right of the slider to display the item instead of adjusting the top.

(P.S. I plan to add a way to stop the slider once it reaches the total number of items)

Below is the React Code:

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

class Item extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: 1,
      top: "0px",
    };
  }

  onClickSlide = (_) => {
    const item = this.state.id;
    this.setState({ top: item * 200 * -1 + "px" });
    this.setState({ id: item + 1 });
  };

  render() {
    let dang = [
      { title: "Header 1", content: "Lorem ipsum proin gravida" },
      { title: "Header 2", content: "Lorem ipsum proin gravida" },
      { title: "Header 3", content: "Lorem ipsum proin gravida" },
      { title: "Header 4", content: "Lorem ipsum proin gravida" },
    ];

const item = this.state.id;
let innerStyle = {top: item * 200 * -1 + "px"};

return (
  <div className="Outer">
    
    <div className="inner" onClick={this.onClickSlide} style={{ top: this.state.top }}>
      {dang.map((data, i) => {
        return (
          <div className="items">
            <h3>{data.title}</h3>
            <h3>{data.content}</h3>
          </div>
        );
      })}
    </div>
  </div>
);
 }
}

export default Item;

Here is the CSS:

.Outer {
  display: block;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.inner {
  /* display: block; */
  position: absolute;
  transition: all 0.5s;
}

.items {
  display: inline-block;
  width: 200px;
  height: 200px;
  vertical-align: top;
}

Answer №1

Great news! After some experimentation and referencing other carousel examples, I have successfully created my own version. While there is always room for enhancement, here is the foundation of my carousel. The concept involves a lengthy container where all images flexibly align next to each other. By utilizing the CSS property "translate," each image can be moved left or right based on the direction clicked.

Check out the React JS implementation below:

 export default () => {
  const [translate, setTranslate] = useState(0);

  const handleClickBtn = (direction) => {
    if (direction === "right") {
      setTranslate({ translate: translate - 100 });
    } else {
      setTranslate({ translate: translate + 100 });
    }
  };

  return (
    <div className="banner-carousel">
      <button
        className="carousel-button btn-left"
        onClick={(_) => handleClickBtn("left")}
      >
        Left
      </button>

      <div className="carousel-container">
          <div
            className="slide"
            style={{ transform: `translateX(${translate}vw)`}}
          >
            <img className="carousel-image" src="https://www.publicdomainpictures.net/pictures/40000/nahled/random-texture.jpg" />
          </div>

          <div
            className="slide"
            style={{ transform: `translateX(${translate}vw)`}}
          >
            <img className="carousel-image" src="https://www.publicdomainpictures.net/pictures/40000/nahled/random-texture.jpg"/>
          </div>

          <div
            className="slide"
            style={{ transform: `translateX(${translate}vw)`}}
          >
            <img className="carousel-image" src="https://www.publicdomainpictures.net/pictures/40000/nahled/random-texture.jpg"/>
          </div>
      </div>

      <button
        className="carousel-button btn-right"
        onClick={(_) => handleClickBtn("right")}
      >
        Right
      </button>
    </div>
  );
};

Below is the SCSS styling:

.banner-carousel {
  height: 720px;

  .carousel-button {
    cursor: pointer;
    position: absolute;
    top: 45%;
    color: #fff;
    z-index: 100;

    &.btn-left {
      left: 25px;
    }

    &.btn-right {
      right: 25px;
    }
  }

  .carousel-container {
    display: flex;
    width: 10000px;

    .slide {
      width: 100vw;
      height: 720px;
      transition: transform 0.25s linear; 

      .carousel-image {
        width: 100%;
      }
    }
  }
}

There is still room for improvement, so I may revisit and update this in the future. If you have any suggestions, feel free to share!

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

Issues arise with the behavior of Bootstrap design when adapting to different screen sizes, as well as

I am currently working on designing my personal portfolio using Bootstrap. I have made some progress with the setup, but I am encountering some issues. When I resize the window, the top menu collapses into a button. However, when I click on the button, n ...

npm encountered an error due to reaching an unexpected end while parsing JSON near the URL for openpgpjs.org

Just starting out with React and diving into a new project! npm version: 6.4.1 create-react-app version: 2.1.8 node version: 10.15.0 When I tried running create-react-app newApp, encountered the following error: npm ERR! Unexpected end of JSON input w ...

Seeking assistance in creating custom tabs for integration with a jQuery tabs plugin

Attempting to navigate the world of CSS as a newbie, I find myself struggling with creating tabs. Our current tab setup can be viewed here, but unfortunately, these tabs are created using an unattractive <table> tag. Below is the code responsible fo ...

What are some tips for designing HTML email templates?

Check out this example of an HTML email <div style="width:650px;"> <div class="begining"> <p> Dear <span>' . $name . '</span><br/>Thank you for your booking </p> & ...

How can I make the sort icon in a Material UI Datagrid column always visible?

Check out this codesandbox link. I'm currently working on enabling sorting by first name and last name in the default Datagrid. However, the sort icon only appears when hovering over it. Is there a method to make it always visible? Appreciate any assi ...

What causes the card to exceed the boundaries of its parent column?

My Form elements seem to be misaligned and not fitting correctly. .h-100 is used for the blue navigation background to occupy the full height of the screen. An answer explaining why my code snippet is not working would be appreciated. View Plunker here ...

Has the PureRenderMixin mixin become outdated?

When working with stateless functions in React for render-only components, is the PureRenderMixin still necessary? If it does have a role to play in contemporary container/stateless React setups, what exactly is that role? ...

How can images be resized according to screen resolution without relying on javascript?

Looking to use a large banner image on my website with dimensions of 976X450. How can I make sure that the image stretches to fit higher resolution monitors without using multiple images for different resolutions? ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

Customize the default classes for DataGrid in Material UI

Attempting to customize the CSS properties in the "DataGrid" Material UI, specifically adjusting font weight and overflow of the header. Below is the JSX code snippet: import React, {useState, useEffect} from 'react'; import {DataGrid, GridToolb ...

Determine the height of the left div, which is set to auto, and apply the same height to the right div, which has overflow set

I am facing an issue that needs a solution. I need to ensure that two div elements have the same height. The left div should have 'auto' height while the right one must match it. Moreover, the right div contains 14 nested divs that need to be scr ...

Employ the find() function to ascertain the result of a condition

I'm struggling to grasp how to utilize the find() method in a conditional statement. In simple terms, I want the conditional to evaluate as true if the value of item.label is equal to the value of e.target.value. if (this.props.Items.find(item => ...

Backdrop behind Material-UI Drawer Component

Struggling with implementing the semi-transparent background overlay for the open side menu in a React application using material-ui. Any suggestions on how to achieve this? http://www.material-ui.com/#/components/drawer ...

What is the best way to transform this component into a function rather than a class?

import React, { Component } from "react"; class ChatHistory extends Component { render() { const messages = this.props.chatHistory.map((msg, index) => ( <p key={index}>{msg.data}</p> )); return ( <div ...

Can the behavior of "flex-end" be emulated in :before and :after pseudo-elements?

I have come across a piece of code that creates a checkbox using the pseudo-elements :before and :after, along with a hidden input to handle the selection logic. The current setup works fine and behaves as expected. However, I am curious if it is possible ...

What could be causing the sidebar animation to glitch in Internet Explorer when using an *ngFor loop?

I am facing an issue with my animation where it works perfectly in Chrome but not in IE. The desired effect is to slide a panel into view from outside the browser window, and upon clicking the exit button or <div> covering the rest of the page, the p ...

Stretch a component outside of the bootstrap container

Currently, I am working on a mockup using Bootstrap 4 and have encountered an unusual element inside the container where the background extends beyond the container. I'm not sure how to address this issue effectively. I attempted to use position: abso ...

JavaScript: AWS Amplify: Retrieving the User ID (Sub ID) Following User Registration. Post Registration, Not to Be Confused with Sign In

Currently, I am utilizing the authentication module from AWS Amplify. One question that has been on my mind is how to obtain the userID once a user signs up. While it is possible to retrieve the ID after a user signs in, I am specifically interested in re ...

Tips for Incorporating HTML Code into an ASP Button's Text Attribute

How can I add a symbol to a button's text without it showing as blank? The symbol in question is an arrow, which you can find here. <asp:button id="btnAdd" runat="server" class="next"/> CSS: .next { content = &#10095; width:50px; } ...