개발조각

[react-device-detect & video-react] 비디오 배경만들때 pc일때는 pc비디오, mobile일때는 mobile비디오 나오게 하기 본문

라이브러리

[react-device-detect & video-react] 비디오 배경만들때 pc일때는 pc비디오, mobile일때는 mobile비디오 나오게 하기

개발조각 2023. 9. 21. 00:47
728x90
반응형

회사에서 랜딩페이지를 만들면서 비디오 배경 만들 때 골머리를 많이 때렸다...

 

만들어야 되는 기능


pc일 때는 배경이 pc비디오가 나오게 모바일일 때는 배경이 모바일비디오가 나오게 해야 된다.

 

과정 1


처음에 단순하게 반응형으로 처리했다가 사수분한테 혼났다ㅎㅎ

<video
	autoPlay={true}
	loop={true}
	muted={true}
	playsInline={true}
>

	<source className="pc" src="pc비디오.mp4" type="video/mp4"/>
	<source className="mobile" src="모바일비디오.mp4" type="video/mp4"/>
</video>

이렇게 만드는 건 옛날 방식이라고 이렇게 하면 안 된다고 했다...

 

과정 2


react-device-detect를 이용해서 아래와 같이 수정해 주었다.

https://www.npmjs.com/package/react-device-detect

 

react-device-detect

Detect device type and render your component according to it. Latest version: 2.2.3, last published: 7 months ago. Start using react-device-detect in your project by running `npm i react-device-detect`. There are 1009 other projects in the npm registry usi

www.npmjs.com

import { isAndroid, isIOS, isMobile } from "react-device-detect";
<video
	autoPlay={true}
	loop={true}
	muted={true}
	playsInline={true}
>
	<source
	src={isMobile ? "모바일비디오.mp4" : "pc비디오.mp4"}
	type="video/mp4"
	/>
</video>

react-device-detect는 마운트(새로고침)될 때만 적용이 되고, 만약 pc에서 화면 사이즈를 줄일 경우 적용되지 않는다.

사용자들은 pc일 때는 pc 모바일일 때는 모바일에서만 사용하지 화면사이즈를 줄여가면서 확인하고 체크하지는 않기 때문에 크게 신경을 안 써도 된다.

사이즈를 조절하고 개발자 도구를 켜는 건 개발자만 한다는 사실을 잊으면 안 된다!

 

이렇게 하면 끝이 났으면 좋겠지만 이렇게 적용하면 모바일시 새로고침을 하면 빈화면이 나온다.

확인해 보니 src가 빈값이 나오는 이슈가 발생했다.

 

과정 3 (해결방안)


이 이슈를 해결하기 위해 다시 라이브러리를 찾았는데 찾은 라이브러리는 video-react이다.

https://www.npmjs.com/package/video-react

 

video-react

Video-React is a web video player built from the ground up for an HTML5 world using React library.. Latest version: 0.16.0, last published: 10 months ago. Start using video-react in your project by running `npm i video-react`. There are 223 other projects

www.npmjs.com

import { isAndroid, isIOS, isMobile } from "react-device-detect";
import { Player, ControlBar } from "video-react";
<div className="video-bg">
    <Player autoPlay={true} loop={true} muted={true} playsInline={true} controls={false}>
        <ControlBar disableDefaultControls={true} />
        <source src={isMobile ? "모바일비디오.mp4" : "pc비디오.mp4"} />
    </Player>
</div>

이유는 모르겠지만 이렇게 하면 잘된다...

아마 src에서 {}하고 삼항연산자를 쓰는 게 리액트의 방식이라 그런지 video태그에서 인식을 못하는 것 같다.

그래서 라이브러리를 이용해서 컴포넌트를 사용하면 잘된다.

728x90
반응형
Comments