DEV Community

Cover image for TIL - Javascript Animation on Background-Pics in React
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

TIL - Javascript Animation on Background-Pics in React

Animated Background-Pics

To get the pic to cover the whole screen on different screen sizes it is good to attach it to the <body> tag.
The library Body-Classname provides a declarative way to specify document.body.className. I additionally used Emotion to write css styles with JavaScript.

/** @jsx jsx */
(before ->  import React from 'react'; for emotion library ) 
import BodyClassName from 'react-body-classname';
import { jsx } from '@emotion/core'
(...)

let sectionStyle = (process.env.PUBLIC_URL + `/images/${image()}.png`) ;

let errorStyle =(process.env.PUBLIC_URL + `/images/error.gif`) ;
(...)

 <BodyClassName className="container" css={{ backgroundImage: `url("${errorState ? errorStyle : sectionStyle}")` }}>
(...)
 <BodyClassName/>
Enter fullscreen mode Exit fullscreen mode
body{
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    min-height: 100%;
    min-width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Where to put your images?

<src>

  • have an image-folder in the source folder and access it from there -> <img src="/images/imagename.png" alt='image'/>

<public>

  • The react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. <img src={process.env.PUBLIC_URL + '/img/logo.png'} />

Top comments (0)