CSS animation disappears after array is modified

I created a React application that manipulates an array of letters by shifting and unshifting them. The transition animation is triggered when the user clicks on the next and back buttons. Although the array is modified correctly, the transition effect only works when clicking next. I suspect that this issue might be related to something fundamental rather than specific to React, although I have ensured that the key is unique to prevent re-rendering.

// here's where the problem lies.
clickLeftRightHandler = () => {

    const { list } = this.state;
    // Could redrawing occur due to using slice or shifting the array? Or is it related to CSS?
    const newList = [list[list.length-1], ...list.slice(0, -1)];

    this.setState({list : newList});

}

Link to Code: https://stackblitz.com/edit/react-7nsrjg

Any assistance would be greatly appreciated!

Answer №1

To achieve the desired result, you can make use of the unshift method:

clickLeftRightHandler = () => {

    const { list } = this.state;
    const newList = list.slice(0, -1);

    // Add the last item to the beginning of the new list
    newList.unshift(list[list.length-1]);   // <-- this line here 
    this.setState({list : newList});
}

Here's a working example for reference.

edit

If you're wondering why it works, one possible explanation is that adding an extra character at the end might affect the animation timing. You can try appending a space like this:

newList.unshift(list[list.length-1]+' ');

Check out this example to see the difference in action. It's quite intriguing!

Answer №2

The reason behind the malfunctioning animation was uncovered to be linked to the key assigned to the Alphabet Component. To resolve this, an index state was introduced to ensure that the key would receive a fresh identity distinct from the previously used one.

It is worth mentioning that the revised demonstration by @yuvi also addresses the issue by introducing a new string for the key, ensuring its uniqueness.

Check out the latest example

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

Learn how to cycle through three different texts that appear in the same spot using smooth transitions

I am working with three different rows that contain the Typography component. My goal is to display the first row, followed by the second, then the third, and back to the first one in a continuous loop. All three rows should be shown in the same location, ...

Error: Your Discord bot is unable to send a message as it is empty. Please check Discord

I have been developing a Discord Bot to verify Roblox accounts. Although my script is prepared and the command "-verify" can be executed, an error arises: (node:22872) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use `n ...

HTML code for positioning an image after resizing

Within an HTML page, I have an image that has been resized to a width of 400px using CSS. .cropbox { width: 400px; height : auto; } Additionally, there is a JavaScript function associated with the image that allows users to select a point on the image. T ...

Unusual symbols in angular variable found within an HTML document

Currently in my HTML, I have code like this: <li ng-repeat="favorite in favorites track by $index"> <a ng-href="javascript:void(0)" ng-click="changeSVG(favorite)"> <i class="fa fa-sitemap"></i>{{favorite}} </a> </l ...

Searching by date in MongoDB using Node.js

Does anyone know how to query a mongo collection by date using JavaScript? Here is an example: var startDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours(),0); var endDate = new Date(dateNow.getUTC ...

I keep receiving a 400 error code indicating that the files are empty

Trying to figure out why my images are not uploading on strapi. Could it be that I've misplaced the fileArrayForUpload? Even though it is not empty, could it still be in the wrong place? handleCreateSubmit: const [createProduct] = useMutation(CREATE ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

Challenges with mapping UVs in THREE.js Geometry

I've been attempting to apply a textured mesh with unique UV coordinates for each face, but despite following all the necessary steps, I haven't achieved the desired results. To start, I define the texture coordinates: top_texture_uv = [new THR ...

Developing a vue.js component library without the need for constant rebuilding after every edit

Introduction: I have created two projects using vue-cli ~4.2.0: parent-app - the main project dummylib - a library that is imported by parent-app. It contains several .vue components. Currently, parent-app functions well in dev mode with dummylib being ...

What is the point at which an ES module can import a CommonJS named export?

I encountered an issue with my ES module that relies on a named export from a CommonJS module I created. es.mjs import { MyNamedExport } from './commonjs.cjs'; console.log(MyNamedExport); commonjs.cjs (working version) exports.MyNamedExport = ...

Encountering an unusual reactivity problem involving Firebase (Firestore) when using Vue.js and Vuefire

I'm facing a strange issue and I'm completely stuck. Here is the component in question: <template> <v-card elevation="0"> <h2>Accounts</h2> <v-simple-table fixed-header height="300px"> <template v ...

Close session when browser/tab is exited

After extensive searching online, I have been unable to find a satisfactory solution for ending a session when a browser or tab is closed without requiring the user to log off. I have attempted numerous JavaScript codes that I came across, but none of the ...

Difficulty encountered while trying to link an abstract class with Redux state using redux-thunk

My approach to using redux-thunk and class components in React follows a basic pattern. The code below shows how a class definition MyClass is exported, correctly connected to state through mapStateToProps, and has access to actions from mapDispatchToProps ...

Exploring the relationship between React component inheritance and asynchronous requests

I'm struggling to comprehend why this isn't functioning var link = window.location.href; var array = link.split('/'); var sub = array[array.length-1]; console.log(sub); var name; var posts; var upvotes; var ProfileFiller = React.creat ...

Issue: React child objects are not acceptable (detected: object containing keys {inputList}). To display a group of children, please utilize an array instead

My attempt at creating input fields using key and value pairs has hit a roadblock. Despite thinking it would be straightforward, I am encountering an error that is proving tricky to resolve. import {Form, Input, Button } from 'semantic-ui-react' ...

Developing a production build of a React app on a high-end machine is taking an unexpectedly

Our team is facing challenges with the performance of our production build, as it is taking approximately 20 minutes to complete. We initially suspected that the issue might be related to our local machine's capabilities, so we decided to run the buil ...

Unusual CSS hierarchy observed post AJAX content load

Currently, I am facing a puzzling issue where my CSS rules seem to be losing precedence on a page loaded via AJAX. Despite placing my custom CSS file last in the main page, allowing it to take precedence over any bootstrap styles, after loading new content ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

Developing a Navigation Bar Layout with React Router for Pre and Post Login Scenarios

Seeking assistance on how to structure the React App using React Router <div> <Navbar /> //Display Navbar only for '/' and '/login' <Route path="/" component={IndexPage} /> <Route path=&q ...

JavaScript shows undefined fields for results from Mongoose/MongoDB

Why is the item logging as an object with a parameter, but when trying to access that parameter it's undefined? My attempts so far: console.log(item) => { title: "foo", content: "bar" }, which is fine console.log(typeof item) => object consol ...