본문 바로가기

Language & Framework/React.js

리액트에서 무작위 백그라운드 이미지 설정하기 (feat. styled-components)

새로고침할 때마다 백그라운드가 변경된다.

 

나는 styled-components를 사용했지만 css를 사용해도 가능하다.

다만 각 컴포넌트에 지정해주는 것이 아니라 전역으로 설정이 가능한지, 그리고 inline이 아니라 css 혹은 scss 내에서 설정 가능한지는 모르겠다. 

 

나 같은 경우는 모든 컴포넌트에서 동일한 background-image를 설정해주기 위해 globalStyle에서 background-image를 설정했다.

과정은 다음과 같다. (css or scss를 사용하는 사람도 적용을 원하는 컴포넌트에서 그대로 따라하면 된다. 전역 설정 방법은 모름.)

 

 

1. 원하는 이미지를 import한다.

import img1 from "../img/background1.jpeg";
import img2 from "../img/background2.jpeg";
import img3 from "../img/background3.jpeg";
import img4 from "../img/background4.jpeg";
import img5 from "../img/background5.jpeg";

 

2. import해온 이미지를 array에 모은다.

const backgroundArr = [img1, img2, img3, img4, img5];

 

3. math.random() 함수와 math.floor() 함수를 이용해서 인덱스 지정을 위한 난수 생성기를 만들어준다.

const randomIndex = Math.floor(Math.random() * backgroundArr.length);

참고로 Math.random은 0 이상 1 미만의 랜덤한 난수를 생성해주는 함수이며, Math.floor는 소수점을 내려서 정수로 만들어준다.

위의 randomIndex는 (소수점 떼고 정수로 반환해주세요 ( 0.0000... ~ 0.99999... * 5 )) 라고 읽으면 된다. 그러면 0부터 4까지의 수가 임의로 생성되는 것.

 

4. 위에서 만든 Array와 난수 생성기를 결합해서 랜덤으로 이미지를 선택하는 변수를 만들어준다.

const backgroundImg = backgroundArr[randomIndex];

 

5. 해당 변수를 원하는 위치에 넣어주면 끝.

 

5-1. styled-components의 경우 

const GlobalStyle = createGlobalStyle`
body {
  background-image: url(${backgroundImg});
  margin:0px;
  width:100vw;
  height:100vh;
  background-size: cover;
  background-repeat: no-repeat;
}`

// or

const Container = styled.div`
  background-image: url(${backgroundImg});`
  
// ..

 

5-2. styled-components를 사용하지 않을 경우?

 

function MainItems() {
  return (
    <section style={backgroundImage: `url(${backgroundImg})`}>
      <Clock> 00:00 </Clock>
      <p> Hello, {userID} </p>
      <Focus>
        <p>What is your main focus for today?</p>
        <input />
      </Focus>
    </section>
  );

개인적으로 style을 inline으로 작성하는 것을 좋게 생각하지 않아서 styled components 쪽이 나은 것 같다.

JS에서는 그냥 DOM에 직접적으로 style을 지정해줄 수 있어서 이런 식으로 할 이유가 없었는데 이런 건 리액트가 더 불편한 것 같기도.

아니면 다른 방법이 있는 건지 아직 리액트 애기라서 모르겠다. 🐥