"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > View Transition Animation in React.js App

View Transition Animation in React.js App

Published on 2024-08-27
Browse:440

View Transition Animation in React.js App

Other day me want create quick remove items from list animation for site. This time skip React Transition Group, try new View Transition, save time.

Why write lot code when few code do trick.

View Transition API Chrome only, but me no care.

Crux is document.startViewTransition.

But need establish DOM before state, after state, but React.js don’t allow.

React.js reactive. Not synchronous. document.startViewTransition need synchronous.

Ask Google learn:

import { flushSync } from "react-dom";

flushSync(() => setState(...));

Me write hook:

import { useState } from "react";
import { flushSync } from "react-dom";

export const useViewTransition =
  typeof document !== "undefined" && "startViewTransition" in document
    ? (newValue: T) => {
        const [value, setValue] = useState(newValue);
        if (value !== newValue) {
          document.startViewTransition(() => {
            flushSync(() => {
              setValue(newValue);
            });
          });
        }
        return value;
      }
    : (value: T) => value;

If use useQuery

const { data: newMsgs } = useQuery({
  queryKey: ["msgs"],
  queryFn: msgs.all(25)
});

const msgs = useViewTransition(newMsgs);

return (
  
    {msgs?.map(item => (
  1. {item.title}
  2. ))}
);

Now when useQuery update, hook call document.startViewTransition then setState.

Need global CSS

Me add global.css:

@supports (view-transition-name: none) {
  ::view-transition-group(root) {
    animation-duration: 0s;
  }
  ::view-transition-group(.mymsg) {
    animation-duration: 0.4s;
  }
}

This tell Chrome: don’t transition whole page, only transition list items.

Now message list animation work. Very nice.

Release Statement This article is reproduced at: https://dev.to/ctnr/using-view-transitions-in-reactjs-1064?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3