React Aquarium

Michael Ries
Code Monkey
3 min readOct 9, 2017

--

I’ve been working on a project called ‘Dive Logger’ that is an online resource for SCUBA divers to track data related to their dives. It’s rather bare-bones so far, and I’ve been thinking about how to spice it up a bit. This week I decided that it would be fun to add some fish swimming around in the background. You can see the end product here: Dive Logger. I like how it turned out, so I thought I’d share with you how it works.

The Dive Logger project is built using React and Redux. Adding the fish involved creating 2 new components, the <Aquarium/> and the <Fish/>. The <Fish/> and the <Aquarium/> are independent of each other and the rest of the app, so ‘installing’ them turned out to be really easy.

Designing the <Aquarium/>

The <Aquarium/> is a simple presentational component that contains the fish and several full-screen <div>s of ‘water’ with 10% opacity and at various z-indexes that are used to provide the illusion of depth into the screen. To prevent the aquarium (and fish) from interfering with the app, all of the elements in the <Aquarium/> are behind the main app.

Adding the <Fish/>

The fish are more complicated. Each fish tracks its own location, velocity, direction, and has functions for moving and randomly choosing a new direction and velocity. Each fish uses the react component lifecycle methods componentDidMount and componentWillUnmount to start and remove a timer, respectively.

The <Fish/> can move in 3 dimensions, including into and out of the screen. As it goes ‘deeper’ into the screen, the size is scaled smaller and the z-index becomes more negative so that it goes behind more the ‘water’ <div>s. Because each ‘water’ <div> has a 10% opacity, this causes the fish to appear as though it is further away.

The <Fish/> knows to turn around when it reaches the edge of the window. If a user resizes the window, however, a <Fish/> can find itself outside of the current viewport. If this happens, it will reappear inside the viewport at the minimum z-index, making it seem as if it is a new fish that just swam into view from far away. This behavior is handed by the relocate() function.

This certainly isn’t the most elegant code. There are many opportunities to refactor, but this illustrates the basics. I created a development sandbox here.

Parting Words

This is just a starting point. One can imagine adding corals or rocks in a footer at various ‘depths’, for example. I’ve considered adding bubbles that randomly spawn from the bottom of the screen and move upwards. But I think this is a good place to start.

Also, please check out my earlier posts:

Object Composition in Javascript

Javascript ‘Classes’ and Prototypal Inheritance

Understanding Closures in Javascript

Form Validation in React

OAuth in React/Redux Applications

Resources

Best Animations

--

--

Michael Ries
Code Monkey

Solving complex problems one simple problem at a time.