In the previous ScrollTrigger tutorial, we have covered the basics. If you are new to GreenSock and ScrollTrigger read it first and then come back here.
Continue reading
In the previous ScrollTrigger tutorial, we have covered the basics. If you are new to GreenSock and ScrollTrigger read it first and then come back here.
Continue readingAfter a long time in making, I am very excited to announce that the new lineup of my premium online courses will be available for purchase from the 18th of August 2020.
Practical GreenSock is a bundle of 3 online courses teaching you how to create more advanced animations and effects using GreenSock, ScrollTrigger and vanilla JavaScript.
All 3 courses are suitable for intermediate to advanced developers and designers.
Here is the breakdown of all 3 courses included in Practical GreenSock, watch the first unit from each of them to learn more.
Anyone who has purchased at least one of my “closed” premium courses gets free access to Projects Slider and Pen Reveal from today.
Simply login to your account and start any of these two GSAP3 and ScrollTrigger courses today.
Enjoy this as a gift for all your support over the last few years. Thank you!
To celebrate the re-launch of my premium courses I am also giving away 5 copies of Practical GreenSock.
Congratulations to the winners:
a Rafflecopter giveawayCheers
Petr
This React and Greensock Tutorial is focusing mainly on the basics of targeting elements and using React Hooks with GreenSock.
If you have been following my blog and YouTube channel for a while, you know that I enjoy using React and GreenSock.
They are both very powerful libraries with elegant APIs.
As more and more websites are build using React, it’s important to know how to use GreenSock in the React world.
What will you learn:
Baby steps I know, but lets learn how to walk before you try to run.
If you prefer learning by watching videos, checkout React + GreenSock 101.
I am assuming you already know how to spin up a brand new React project using the Create React App.
npx create-react-app gsap-app cd gsap-app
Now we can install GreenSock through npm and start the app.
npm i gsap npm start
Cool, GSAP is installed lets import it to our App
component.
import React from 'react'; import { gsap } from "gsap"; const App = () => { ... return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> </header> </div> ) }
Firstly we need to get access to the element that we want to animate.
We can use useRef
because our App
component is a functional component.
import React, { useRef } from 'react'; import { gsap } from "gsap"; const App = () => { const headerRef = useRef(null); ... return ( <div className="App"> <header ref={headerRef} className="App-header"> <img src={logo} className="App-logo" alt="logo" /> </header> </div> ) }
We are storing a reference to our header
element in the headerRef
variable.
You can read more about React Refs in the official documentation.
With our header
“selected”, we can create a tween that will play when the component mounts.
import React, { useRef, useEffect } from 'react'; ... const App = () => { ... useEffect(() => { gsap.from(headerRef.current, { autoAlpha: 0, ease: 'none', delay: 1 }); }, []); ... }
Firstly we need to import useEffect
and create our tween inside of it.
The empty array as a dependency of this effect will make sure that our tween runs only on the initial mount
of this component.
If you are new to React Hooks you can check my free online course React 101.
The target for our .fromTo tween is headerRef.current
that is how we can access the underlying DOM element.
Ok, now we have our header fading in with a slight delay, but how do we animate when the state of our component changes?
Lets create a button that will change the background color of the header
.
But we could that with css
class, right? Off course we could, but I thought you are here to learn React + Greensock.
import React, { useRef, useEffect, useState } from 'react'; ... const App = () => { const [background, setBackground] = useState('#5a7d95'); ... const toggleBackground = () => { const color = background !== '#5a7d95' ? '#5a7d95' : '#1b4943'; setBackground(color); } useEffect(() => { gsap.to(headerRef.current, { backgroundColor: background, duration: 1, ease: 'none' }); }, [background]); return ( <div className="App"> ... <button onClick={() => toggleBackground()}>Change background</button> ... </div> ); }
We import useState
, set the default color and create a function toggleBackground
that will toggle the background color between light and dark.
Then inside of a new useEffect
that only listens to the background color change, we are using GreenSock’s .to
tween to animate the background-color to the right value.
Please excuse my non-creative animations today, I am trying to keep the example as simple as possible.
ScrollTrigger is the cool plugin from GreenSock that lets you trigger animations as the user scrolls through your page.
Let have a look how to include ScrollTrigger in your React project and fade in a few section.
import React, { useRef, useEffect, useState } from 'react'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; gsap.registerPlugin(ScrollTrigger); const sections = [ { title: 'Title 1', subtitle: 'Subtitle 1' }, { title: 'Title 2', subtitle: 'Subtitle 2' }, { title: 'Title 3', subtitle: 'Subtitle 3' } ]; ...
We import ScrollTrigger and then register the plugin to make sure it survives the code tree shaking.
For this demo we are hardcoding some content in the sections
array.
const App = () => { ... const revealRefs = useRef([]); revealRefs.current = []; const addToRefs = el => { if (el && !revealRefs.current.includes(el)) { revealRefs.current.push(el); } }; return ( <div className="App"> { sections.map(({title, subtitle}) => ( <div className="App-section" key={title} ref={addToRefs}> <h2>{title}</h2> <p>{subtitle}</p> </div> )) } </div> ); }
Because we want to access multiple sections and trigger them individually, we need to create an array of refs revealRefs
.
As you know from the above header
example we get access to the underlying DOM elements in the .current
property.
That is why we need to create a function addToRefs
and add all our references to the sections to the revealRefs.current
array.
Ok, great. We have access to all sections. Now lets loop over them and create new GSAP tween with scrollTrigger
.
useEffect(() => { ... revealRefs.current.forEach((el, index) => { gsap.fromTo(el, { autoAlpha: 0 }, { duration: 1, autoAlpha: 1, ease: 'none', scrollTrigger: { id: `section-${index+1}`, trigger: el, start: 'top center+=100', toggleActions: 'play none none reverse' } }); }); }, []);
We are looping over the revealRefs.current
array and creating a simple .fromTo tween.
Each sections fades in when top of it is 100 pixels from the center of the viewport.
Again, today I could not think of a more creative way than just simply fading in a bunch of dummy sections.
Do you want to learn more about React or GreenSock? Check out my free online courses React 101 and GreenSock 101.
Quite a long tutorial, but I hope that this guide will help you with implementing GreenSock in your React projects.
Do you have any questions related to GSAP and React? Let me know in the comments.
In the previous page transitions tutorial we have created a simple “take over” effect.
Today we will explore a little bit more about Barba.js and GreenSock and create a circular page transition.
What you will learn in this page transitions tutorial:
The general setup of Barba.js is the same as in the previous tutorial.
barba.init({ transitions: [{ async leave({trigger}) { await loaderIn(trigger); }, enter({next}) { loaderAway(next); } }] })
We have two transitions leave()
and enter()
, but this time we are passing trigger
to the loaderIn
function and next
to the loaderAway
function.
Each Barba.js hook receives the same data argument that contains the current
and next
page properties, it also includes trigger
that is the link that triggered the transition.
You can read more about the Barba Hooks in the official documentation.
function loaderIn(trigger) { // get the size of the clicked trigger element const { height, width, top, left } = trigger.getBoundingClientRect(); const triggerTop = Math.floor(top); const triggerLeft = Math.floor(left); const triggerWidth = Math.floor(width); const triggerHeight = Math.floor(height); // get viewport size, this will be used for scaling up the loader const viewportHeight = window.innerHeight; const viewportWidth = window.innerWidth; const loaderSize = viewportHeight > viewportWidth ? viewportHeight*2 : viewportWidth*2; ... }
We are firstly getting the dimensions
of the trigger
and its top
and left
offset relative to the viewport using the javascript getBoundingClientRect()
method.
Secondly, we are getting the size of the viewport to be able to resize the loader accordingly.
Because the loader will always scale up from the center of the clicked element we need to make sure it is twice the size of the viewport.
Now we need to create a GreenSock timeline that will scale the loader up.
function loaderIn(trigger) { ... const tl = gsap.timeline(); tl .set(loader, { autoAlpha: 1, x: triggerLeft + (triggerWidth/2), y: triggerTop + (triggerHeight/2), width: loaderSize, height: loaderSize, xPercent: -50, yPercent: -50 }) .fromTo(loader, { scale: 0, transformOrigin: 'center center' }, { duration: 0.8, scale: 1, ease: 'power4.out' }); return tl; }
Firstly we use the .set tween to set the right position of the loader and resize it according to the viewport.
We use xPercent: -50
and yPercent: -50
to center, the middle of the loader in the center of the clicked link.
The .fromTo tween scales the loader from 0
to 1
.
Regardless of where the link is on the page, the loader will always scale up from there and cover the whole screen.
Still with me? Lets keep going.
If you are new to GreenSock, checkout out my GreenSock 101 online course.
Now let’s try to change the body class and display the correct background colors as defined in the stylesheet.
.is-home { background: #1f213f; } .is-page-2 { background: #1c323d; }
Remember Barba.js only replaces the content of the data-barba="container”
. This means that the body class would stay the same when navigating between the pages.
We have to manually update it like this:
function loaderAway(next) { document.body.removeAttribute('class'); document.body.classList.add(next.container.dataset.class); ... }
We are passing the next
page to the loaderAway(next)
function.
Inside of it, we are firstly removing the class
attribute from the body
tag and then applying the class that we have defined on the incoming page container
as data-class="is-page-2”
.
This will make sure that the body class is updated before we reveal the incoming page.
Now we have the whole page covered by the scaled-up loader
, Barba updated the page under the loader and we are ready to reveal it.
The loader
is a simple div, with a border-radius
set to 100%
to appear as a circle.
function loaderAway(next) { ... const h1 = next.container.querySelector('h1'); const p = next.container.querySelectorAll('p'); const img = next.container.querySelector('img'); const tl = gsap.timeline(); return tl.to(loader, { duration: 1, scaleX: 0.5, // squash the loader scaleY: 0.1, // squash the loader yPercent: 0, // move it down ease: 'power4.inOut' }).fromTo([h1, p, img], { autoAlpha: 0 }, { duration: 0.9, autoAlpha: 1, stagger: 0.02, ease: 'none'}, 0.3); }
We can access the content of the incoming page by getting the right selectors from next.container
.
Then we can reveal it in whatever fashion we want.
The .to tween above is squashing it down and moving it away from the viewport using the yPercent: 0
.
With a slight 0.3s
delay and a short stagger
offset we are also fading the content in.
And that is it, now you know how to create a circular page transition using Barba.js and GreenSock. If you are new to GreenSock, checkout GreenSock 101 where you can learn even more about this powerful animation library.
Have you seen any cool page transitions that you would like to see covered in my future page transitions tutorial?
Let me know in the comments.
Page transitions are a thoroughly popular tool to help make your website stand out!
Smooth, fluid, and creative transitions often sets awarding winning websites apart from the rest.
In this tutorial we will demonstrate how to create a simple page transition using Barba.js and GreenSock.
What you will learn:
Whilst creating page transitions may sound difficult, Barba.js makes the process incredibly easy.
There are two types of page transitions:
Now, let’s walk through the process of creating a loading screen page transition on a project with 2 static html pages.
/css/app.css /js/main.js index.html page2.html
Firstly, we will create a loading screen .loader
. This will be a container that will cover our screen while Barba.js is loading the next page.
<div class="loader"></div> .loader { position: fixed; width: 100vw; height: 200vh; pointer-events: none; background-color: #FFF6ED; z-index: 1; visibility: hidden; opacity: 0; }
We will make it position: fixed
and the height twice as tall as the screen height: 200vh
. This is because we will soon be slightly rotating it. Without any rotation a height: 100vh
would be enough to cover the whole screen.
Opacity
and visiblity
are set to 0
and hidden
, because we don’t want to see a flash of the loader before GSAP scales it down.
// reset position of the loading screen gsap.set(loader, { scaleX: 0, rotation: 10, xPercent: -5, yPercent: -50, transformOrigin: 'left center', autoAlpha: 1 });
In the main.js
we are rotating the loader and setting the scaleX
to 0
to make it invisible for the user. At the same time we are setting visibility: visible
and opacity: 1
using GreenSock’s handy autoAlpha
property.
Include Barba.js at the bottom of both HTML files.
<script src="https://unpkg.com/@barba/core"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script> <script src="js/main.js" defer></script>
I am also including GreenSock because Barba.js is not an animation library – it only takes care of content loading.
Your preferred animation library and style of page transition is completely up to you.
I tend to choose GreenSock for its flexibility and easy functionality. I have also become very familiar with it.
If you want to learn how to use GreenSock from scratch, check out GreenSock 101.
There are plenty of other animation libraries that would also work well, such as popmotion, animejs, mojs or spirit.
Barba.js requires two special data-attributes somewhere in your markup.
<body data-barba="wrapper"> <!-- content that stays the same on all pages - eg. header --> <div id="intro" data-barba="container"> <!-- content that will change from page to page --> </div> <!-- content that stays the same on all pages - eg. footer --> </div>
data-barba="wrapper"
specifies the main wrapper of your page structure. This could be in the body
or any other HTML element.
data-barba="container"
is a section of your page which will be “reloaded or updated,” with the incoming content from the other page.
Anything outside of the container
will not change between the page transitions.
You can use any markup you want, the only requirement is that the wrapper
always needs to wrap the container
.
barba.init({ transitions: [{ async leave() { await loaderIn(); }, enter() { loaderAway(); } }] });
In the main.js
, we then initiate Barba.js to create our transition.
leave()
will be executed first, followed by enter()
.
loaderIn()
is a function that returns GSAP tween which stretches our .loader
to cover the whole screen.
loaderAway()
is a function that returns GSAP tween which scales the loader back to scaleX:0
, when the new page is loaded underneath it.
Now let’s have a look at the two tweens which create the transition.
function loaderIn() { // GSAP tween to stretch the loading screen across the whole screen return gsap.fromTo(loader, { rotation: 10, scaleX: 0, xPercent: -5 }, { duration: 0.8, xPercent: 0, scaleX: 1, rotation: 0, ease: 'power4.inOut', transformOrigin: 'left center' }); }
fromTo
tween takes care of the first half
of transitions and covers the screen when it’s completed.
We are setting the transformOrigin
to be 'left center'
. This makes it grow from left to right.
function loaderAway() { // GSAP tween to hide loading screen return gsap.to(loader, { duration: 0.8, scaleX: 0, xPercent: 5, rotation: -10, transformOrigin: 'right center', ease: 'power4.inOut' }); }
This tween reveals the new page which was loaded underneath the loader by Barba.js.
By changing the transformOrigin
to 'right center'
we create the effect of the loader disappearing on the right side of the screen.
Barba.js also gives you access to specific lifecycle methods or hooks that you can tap into.
One common example would be to add css class to your page to prevent users from double clicking on links.
// do something before the transition starts barba.hooks.before(() => { document.querySelector('html').classList.add('is-transitioning'); }); // do something after the transition finishes barba.hooks.after(() => { document.querySelector('html').classList.remove('is-transitioning'); });
.is-transitioning { pointer-events: none; cursor: progress; }
Another example would be to enable scrolling to the top of the newly loaded page. We can use .enter
hook for that.
// scroll to the top of the page barba.hooks.enter(() => { window.scrollTo(0, 0); });
This may have been just a basic example, however I hope you can now see implementing page transitions can be a simple task!
The ultimate key is to master Barba.js and an animation library of your choice. If you’d like to go with GreenSock, learn everything you’ll need to know at GreenSock 101.
Today we really only scratched the surface of page transitions. It is a broad area, with lots of creative options out there.
So, if you have you seen other interesting page transitions you would like to learn about, please let me know! I’d be happy to make more in-depth page transition tutorials.
I am currently in the planning phase of my new premium courses. Please answer the following questions, so that I can create the ideal course for you.
Are you new to React Hooks or would you like to know how to use GreenSock with React?
Then you should definitely understand what React Hooks are and how to use them.
In this React Hooks tutorial will learn:
useState()
useEffect()
In short React Hooks let you use state and side effects in a functional components, something what was not possible before.
Before React Hooks were introduced to the world, this would be your workflow:
Now with React Hooks it looks much more streamlined:
React Hooks let you manage the state and react to state changes in functional components.
You can read more about React Hooks from the official documentation.
Now lets explore the most common state management use cases in React components.
Imagine that we have a simple React component that needs to be either collapsed or expanded.
import React from 'react'; const Collapsible = () => { return ( <div className="isExpanded"> <h1>Item title</h1> ... </div> ) }
We would need to rewrite this into a class component if there were no React Hooks.
Luckily we have useState
React Hook.
import React, { useState } from 'react'; const Collapsible = () => { const [state, setState] = useState(false); return ( <div className={state ? 'isExpanded' : null}> <h1>Item title</h1> ... </div> ) }
We are importing useState
from React and then creating a default state
with the value of false
.
Then we have access to the state variable
and can render a css class
when required.
If we wanted our component to be expanded by default we would set it to true
by default.
state
and setState
names are customisable names, you could call them whatever you like. color, setColor
or user, setUser
would do the same thing.
You get the point of sticking to a clear naming here.
state
is the name of the stored variable and setState
is a function that updates the value of this variable.
To change the value we could add onClick event to the h1
and toggle the value to the opposite true
or false
.
import React, { useState } from 'react'; const Collapsible = () => { const [state, setState] = useState(false); return ( <div className={state ? 'isExpanded' : null}> <h1 onClick={() => setState(!state)}>Item title</h1> ... </div> ) }
Now we are managing the internal state of our component using the useState
React Hook.
You are not limited to a single value for your state, you can store objects, arrays or even nested objects.
Here is an example of a property
object
being stored in the state.
const [property, setProperty] = useState({ name: 'Hotel Heaven', id: 'hh123', location: 'Collins Street' });
Another React Hook that you will need to master is useEffect()
.
It hooks into your React component in the same way as componentDidMount
, componentDidUpdate
, and componentWillUnmount
used to.
Here is an example component that fetches Top board games from Board Game Geek.
import React, { useState, useEffect } from 'react'; const TopGames = () => { const [games, setGames] = useState([]); useEffect(() => { fetch("https://bgg-json.azurewebsites.net/hot") .then(response => response.json()) .then(data => setGames(data)); }); return ( <div> { games.map(game => <p>{game.title}</p>) } </div> ) }
We are importing useEffect
React hook and then inside of it we are:
data
from an external API andgames
The problem with the above code is that it would create an infinite loop!
The component mounts, we fetch data, the state gets updated, the components updates, we fetch data…and this continues.
By default useEffect()
runs on the first render and on every update.
To make the fetch call only once, we need to supply an empty array as the second parameter.
useEffect(() => { fetch("https://bgg-json.azurewebsites.net/hot") .then(response => response.json()) .then(data => setGames(data)); }, []);
This empty array tells React to run the function inside of it only after the first render, not on update.
In another example we could include a searchTerm
dependency. This would make sure that the fetch call only happens when the searchTerm
variable is updated.
useEffect(() => { fetch(`https://someurl.com/api/${searchTerm}`) .then(response => response.json()) .then(data => setGames(data)); }, [searchTerm]);
searchTerm
is now a dependency for this side effect and unless searchTerm
is updated, the fetch call would not run.
We have mentioned mount
and update
, but where is the componentWillUnmount()
?
If your effect returns a function, it will be executed when it is a time for the component to be unmounted.
useEffect(() => { // do something here first // then console.log when unmouting return (() => {console.log('unmounting now')}) }, []);
This will simply console.log
every-time this component gets removed from the DOM.
I hope that this article clarified a lot of your questions about React Hooks.
They are a great addition to the React API, make your code more readable and reusable.
I am currently re-recording my React 101 to include React Hooks, join me there to learn more.
Are you struggling with anything related to React Hooks? Have you tried to use GreenSock with React? Let me know in the comments.
Greensock Snippets for VSCode are now available for you to instal.
If you are like me, you want to have VSCode snippets extension for every language that you use.
This saves you time typing, speeds up your workflow and prevents you from making unnecessary syntax errors.
If you are keen on GreenSock Animation Platform you can now enjoy brand new GreenSock Snippets for VSCode.
Autocompletion for .to,
.from
, .fromTo
, .set
, import
and timeline
syntax.
Let me know in the comments if I have missed some other snippets that should be also included.
The source code is on Github, feel free to contribute to it