loading...
Cover image for Javascript Animation on Background-Pics in React

Javascript Animation on Background-Pics in React

annequinkenstein profile image Anne Quinkenstein Updated on ・1 min read

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'} />

Discussion

pic
Editor guide