Implementing a Slide animation in React

I am currently working on a carousel feature that includes two buttons, Next and Previous. When the user clicks on Next, I want the carousel to slide from left to right, and when they click on Previous, it should slide from right to left. One important note is that I prefer not to use any external plugins for this functionality.

Regarding my React container:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { prevItem, nextItem, initItem } from '../actions/index';
import { bindActionCreators } from 'redux';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';

class Carousel extends Component{

    previous(){
        this.props.prevItem();
    }

    next(){
        this.props.nextItem();
    }


    componentDidMount(){
        this.props.initItem();
    }

    renderItem(){
        const  {item} = this.props;
        const webLink = `http://${item.link}`;
        const transitionOptions = {
            transitionName: 'slide',
            transitionEnterTimeout: 1000,
            transitionLeaveTimeout: 1000
        };


        return(
            <CSSTransitionGroup {...transitionOptions}>
                <div className="carousel__item" key={item.id}>
                    <img className="carousel__image" src={item.imageurl}/>
                    <div className="carousel__text">
                        <h3>{item.title}</h3>
                        <p>{item.synopsis}</p>
                        <a href={webLink} target="_black">{item.link}</a>
                    </div>
                </div>
            </CSSTransitionGroup>
        )

    }
    render(){


        return(

                <div className="carousel">
                    {this.renderItem()}
                    <div className="carousel__prev" onClick={this.previous.bind(this)}>
                        <i className="fa fa-chevron-left"></i>
                    </div>
                    <div className="carousel__next" onClick={this.next.bind(this)}>
                        <i className="fa fa-chevron-right"></i>
                    </div>
                </div>

        )
    }
}

function mapStateToProps(state){
    return {item: state.item};
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({
        initItem: initItem,
        nextItem: nextItem,
        prevItem: prevItem
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Carousel);

In addition to handling the slide direction, there seems to be an issue with the current slide animation where both the current and previous slides are displayed simultaneously during transition. Do you have any suggestions on how to address this problem while also ensuring correct slide direction?

Answer №1

I recently tackled this issue and found a solution that worked for me.

To achieve the sliding effect in the desired direction, it is essential to maintain a state and apply it to your items using className. Here's an example code snippet:

render () {
    <CSSTransitionGroup
        component={MenuWrapper}
        transitionName="slide"
        transitionEnterTimeout={500}
        transitionLeaveTimeout={500}>
        {this._renderMenu(this.props.selectedSubMenus[menuIdx], menuIdx)}
      </CSSTransitionGroup>
}


_renderMenu = (menu, idx) => {
    return (
        <Menu key={idx} className={this.state.animationDirection} order={idx}>
            content      
       </Menu>
    )
}

Your CSS styling should resemble something like this (note the usage of styled-components):

const menuWidth = "256px";
const MenuWrapper = styled.div`
    display: flex;
    overflow: hidden;
    max-width: ${menuWidth};
`

const Menu = styled.div`
    min-width: ${menuWidth};
    order: ${props => props.order};
`
.slide-enter.left {
    transform: translate(-100%);
}

// More CSS styles go here...

By utilizing flexbox and setting specific widths, you can address any display issues you may encounter.

I hope this explanation proves helpful.

Answer №2

One way to implement slide animations is by using the Slide component for Dialog in React:

const Transition = React.forwardRef(function Transition(props, ref) {
    return <Slide direction='up' ref={ref} {...props} />
})

<Dialog
    open={open}
    TransitionComponent={Transition} // Apply slide transition 
    keepMounted
    onClose={handleClose}
    aria-labelledby='alert-dialog-slide-title'
    aria-describedby='alert-dialog-slide-description'
    fullWidth
></Dialog>

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

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

IDE type inferences are wrong for the Polymorphic React component

declare const MyComponent = <A extends {id: bigint|number}>(props: MyProps<A>) => React.FC<{}> interface MyProps<A extends {id: number}> { data: A[] orderBy: keyof A } declare const x: { id: number, foo: string }[] const F ...

Aligning an element vertically with the surrounding text on the same line

Trying to incorporate inline input range elements in a way that aligns with the line while also aligning with the right edge of the outer div has proven to be challenging. The HTML on the site is formatted using prettify, resulting in <span> elements ...

What could be causing the bullet not to appear in Internet Explorer 6

It is visible in Firefox, but not in IE (specifically IE6). <style type="text/css"> li { list-style-type:disc; } </style> <div style="margin: 2px auto 15px; padding: 5px 0px; width: 480px; text-align: center;"> <ul style="margin: 0; ...

What might be the reason for the border not reaching the bottom of the popup in my chrome extension?

I am currently working on a Chrome extension and using Bootstrap 5 with Sass to style its popup. However, I have encountered an issue where the border of the popup does not extend to the bottom as expected. What could be causing this problem? popup.html & ...

Tips for altering the checked status of a radio input in a React component

I'm working with input type radio buttons const AnswerOptions = (props) => ( <> <input type="radio" id="something" ...

Ways to verify the existence of a particular word within a nested array of objects

I have implemented a text input field and a send button for submitting the entered text. Utilizing the react-mention library, I am able to handle hashtags in the text. As the user types, if they include "#" it displays available hashtags from the data set. ...

Hiding CheckBox items within a CheckBoxList control in ASP.NET

Currently, I am working with a CheckBoxList control that is bound to data and can potentially become very large. In order to manage this, I am implementing a filter mechanism. Here is my approach: foreach( ListItem item in this.UserRolesList.Items ) { ...

I encountered an issue while trying to execute npm run deploy

I've been working on deploying my NextJS app to Github pages. After installing npm gh-pages, I encountered errors every time I tried running npm run deploy. Can anyone offer insight into why this might be happening? When I attempt to execute the com ...

Material-ui does not support autocomplete functionality

I encountered an issue with my JSX file, as I received the following error: Uncaught ReferenceError: AutoComplete is not defined Upon reviewing the code, everything seems correct. Here is the snippet of the code: import React, {Component} from 'r ...

Improving the layout and size of text within input fields

How can we adjust the input text positioning to the right so it's not directly against the edge? Is there a way to move 'searching' 5px to the right? ...

MUIDataTable: How to vertically display a Checkbox List for columns in the viewColumns options of a React application

In my MUI Table Implementation, I have set the options object viewColumns to true. This is supposed to display a popper for choosing columns in a vertical list of checkboxes, but instead, it is showing horizontally as seen in the screenshot below: https:/ ...

MUI components in React failing to render

Recently delved into learning React and utilizing the MUI library. To incorporate the MUI library, I executed the following command: npm install @mui/material @emotion/react @emotion/styled I also added the Roboto font and icons to my project. Subseque ...

How can I ensure that every dependency in my package.json is updated to the newest version using Yarn?

My current react app is using deprecated dependencies and in order to get it functional, I need to update these dependencies to more recent (yet stable) versions. According to a discussion on Stack Overflow, for updating dependencies in package.json to th ...

Instructions for connecting a button and an input field

How can I connect a button to an input field? My goal is to make it so that when the button is clicked, the content of the text field is added to an array (displayed below) const userTags = []; function addTags(event) { userTags.push(event.target.__ wha ...

Managing dynamic backend ports while using axios in React.js- a comprehensive guide!

This morning, I successfully deployed a login app using the MERN stack on Heroku. However, when attempting to log in GET http://localhost:5000/user/login/email/password net::ERR_CONNECTION_REFUSED appeared in the console. I realized that the error w ...

What is the process for verifying the validity of a form in a React application using Material-UI?

How can I validate a form in React with Material UI? I am currently using React Material in my project and have implemented a form with three required fields. I want to be able to check if the form is valid upon clicking the submit button. If you'd l ...

How to disable the underline styling for autocomplete in a React Material UI component

Seeking assistance with removing underline styling and changing text color upon focus within the autocomplete component of React Material UI. Struggling to locate the specific style needing modification. Appreciate any help in advance! ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. https://i.sstatic.net/F3Va4.png What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: h ...

Using a Function to Retrieve Styles in React Native for Android

My goal is to dynamically add views based on the data received from JSON. Each event should be represented with a different color: red or blue. The app will insert a view accordingly. class MainPage2 extends Component { constructor () { super() var s ...