Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router.

My website has pages named A, B, C, and D.

When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to right.

I have come across examples of fade animations, but haven't found any for carousel animations.

Any tips or ideas on how to achieve this using CSS or other methods?

Answer №1

Essentially, one method to achieve this is by utilizing the concept presented in the comment but modified and tailored for react. The key lies in integrating React Router with the carousel component. For the routing aspect, you would implement something similar to:

<Route path="/:page"
       render={
         props => <Layout selectedPage={props.location.state.selectedPage}/>
       }
/>

Next, set up the navigation links as follows:

<nav>
  <ul className="navigation">
    <li>
      <Link to={{pathname: '/mypage', state: {selectedPage: 0}}}>
        My page
      </Link>
    </li>
    // additional links omitted for brevity
  </ul>
</nav>

Below is the main layout component code snippet:

const Layout = props => {

  const [radius, setRadius] = useState(0);
  const [theta, setTheta] = useState(0);

  useEffect(() => {
      const carousel = document.querySelector('.carousel');
      const cells = carousel.querySelectorAll('.carousel__cell');
      const cellWidth = carousel.offsetWidth;
      const cellCount = cells.length;
      setTheta(360/cellCount);
      setRadius(Math.round((cellWidth / 2) / Math.tan(Math.PI / cellCount)));
      carousel.style.transform = 'translateZ(' + -radius + 'px)';
      for (let i = 0; i < cellCount; i++) {
        const cell = cells[i];
        cell.style.opacity = 1;
        const cellAngle = theta * i;
        cell.style.transform = 'rotateY(' + cellAngle + 'deg) translateZ(' + radius + 'px)';
      }
    }, [radius, theta]
  );

  useEffect(() => props.selectedPage !== undefined && rotateTo(props.selectedPage), [props.selectedPage]);

  const rotateTo = n => {
    const carousel = document.querySelector('.carousel');
    const angle = theta * n * -1;
    carousel.style.transform = 'translateZ(' + -radius + 'px) rotateY(' + angle + 'deg)';
  };

  return (
    <div className="scene">
      <div className="carousel">
        <div className="carousel__cell">1</div>
        <div className="carousel__cell">2</div>
        <div className="carousel__cell">3</div>
        <div className="carousel__cell">4</div>
        <div className="carousel__cell">5</div>
        <div className="carousel__cell">6</div>
      </div>
    </div>
  );
};

To style it properly, use the following CSS:

.scene {
  border: 1px solid #CCC;
  position: relative;
  width: 100%;
  height: calc(100vh - 3em);
  margin: 0 auto;
  perspective: 1000px;
}

.carousel {
  width: 100%;
  height: 100%;
  position: absolute;
  transform: translateZ(-288px);
  transform-style: preserve-3d;
  transition: transform 1s;
}

.carousel__cell {
  position: absolute;
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  left: 10px;
  top: 10px;
  border: 2px solid black;
  line-height: 116px;
  font-size: 80px;
  font-weight: bold;
  color: white;
  text-align: center;
  transition: transform 1s, opacity 1s;
}

This implementation simplifies the original example provided in the link, excluding vertical rotation and dynamic cell adding functionalities, while ensuring compatibility with react-router. It may not be perfect, but it gets the job done.

For a complete demonstration, visit https://github.com/luinnarn/carousel-demo.

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

Minimal - Combining a module with a parent component

To provide some background, I am utilizing bootstrap nav pills as triggers for bootstrap collapsibles. This is a simplified representation of the LESS code for bootstraps nav pills: .nav-pills { > li { // Active state &.active > a ...

Issue detected with Bundler: Configuration object is not valid. The initialization of Webpack used a configuration object that does not align with the API schema

I am currently struggling to make my bundler compile properly. When trying to get it working, I encountered this error message in my terminal along with my webpack.config.js file. Here is the issue reported by the terminal: Invalid configuration object. ...

Redux not causing React components to re-render despite changes in store

Hey there, I'm currently diving into the world of Redux alongside React to build a user interface where I can drag and drop files (specifically invoices), display them in a list, and have the ability to edit the metadata associated with each invoice u ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Is it possible to use the HTML script tag without specifying the type attribute as JavaScript? <script type="text/html"></script>?

While examining the source code of an HTML page, I stumbled upon the following snippet: <script id="searchItemTemplate" type="text/html"> <# var rows = Math.floor((Model.RecordsPerPage - 1) / 3 + 1); for (var i = 0; i < rows; ++i){ ...

Attempting to implement a disappearing effect upon submission with the use of JavaScript

I am currently working on implementing a disappearing form feature for a small web application. The idea is that once the initial form is submitted, it will be replaced by a new form. While my current code somewhat works, it only lasts for a brief moment b ...

the components progress down the line

For my right column implementation, I decided to use CSS position:relative and put different elements inside in position:absolute as shown below: <!-- Right Column --> <div class="col-xs-3 pl18" style="position:relative;"> <!-- Withou ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Can anyone provide guidance on how to simulate a click on a JavaScript action for an iPhone?

I am attempting to trigger a click on a "javascript:void(0)" link so that I can retrieve HTML data within the script. Can someone advise me on how to achieve this without using illegal APIs like UITouchEvent, as I only work with NSUrl? Thank you in advan ...

There is a runtime error in Microsoft JScript, as the object does not support the property or method '__defineGetter__'

Upon opening my project in IE9, I encountered the error message: "Microsoft JScript runtime error: Object doesn't support property or method 'defineGetter'." Can anyone provide guidance on how to resolve this issue? ...

Creating a React render method that relies on both asynchronous requests and state changes

Currently, I am immersing myself in the world of ReactJS and Redux. However, I have encountered a hurdle that seems insurmountable to me. In one of my projects, I have a React component that is responsible for fetching data asynchronously. export class M ...

What is the best way to adjust the fill animation of an inline svg based on the movement of the mouse within the parent div?

Can the fill of an inline SVG path be animated to change as the mouse moves across the page? ...

Building a SSR React app using a Static router within an express server

I am facing an issue with server-side rendering a React application on an Express server. I am using Static Router for routing, and while the HTML loads into the browser and routing works fine, the CSS and JS bundles are not loading. In the network tab, th ...

Why am I unable to access the array once the loop has finished?

While utilizing the Google Maps API and AngularJS (1.5.8), I encountered an issue where I couldn't access markers that were created in a loop. The code snippet below is located inside the initMap function: var markers = []; for(var i=0; i<10; i++ ...

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

Utilizing Typescript to Retrieve Keys of Property Arrays in React

My Homepage sends a modal component a profile in this manner. <ProfileOverviewModal open={openProfile} onClose={closeAllModals} onCreateProfile={onCreateProfile} profile={state.profil} /> Within my ProfileOverviewModal.tsx file, ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

Struggling to achieve a horizontal scroll using 'overflowX' in MUI, but unfortunately, it's not functioning as expected

Is there a way to create a properly-sized card with a horizontal scrollbar in a paper format? I've tried using 'overflow' but it doesn't seem to be working in this scenario. import React from 'react'; import { makeStyles } fro ...