# Animate section visibility

Here is a nice little trick to animate sections of content based on visibility on the page in order to give a better experience to the user.

# Snippets

In order to watch for visibility we are using react-visibility-sensor (opens new window)

Run the following command in your project:

npm i react-visibility-sensor

Then you will need to create a new component Visible.js and a style file for it Visible.styles.js.

Paste the following code in Visible.js:

import React, { useState } from 'react'
import VisibilitySensor from 'react-visibility-sensor'
import * as styles from './Visible.styles'

const Visible = ({ children }) => {
  const [isVisible, setIsVisible] = useState(false)

  const visibilityChangeHandler = (changedVisibility) => {

  const visibilityStyles = isVisible && styles.show

  return (
    <VisibilitySensor onChange={visibilityChangeHandler} active={!isVisible}>
      <div css={[styles.visible, visibilityStyles]}>{children}</div>

export default Visible

This uses react-visibility-sensor to detect if the child component of Visible.js is visible in the page and add a change of style when the visibility is changed.

Here is the our proposed styles to go with it, in Visible.styles.js, paste:

export const visible = {
  opacity: '0',
  top: '50px',
  position: 'relative',
  transition: 'all 0.4s ease-in-out',

export const show = {
  opacity: '1',
  top: '0px',

Of course this can be modified to be any other animation you would like.