[React] Styled-Component 이미지 경로 지정

Narcoker·2023년 5월 12일
0

ErrorHandling

목록 보기
8/14

에러사항

css 파일을 Styled-Component화 하는 리팩토링 과정에서
background-image의 경로를 다음과 같이 상대 경로를 넣으니
이미지가 출력되지 않았다.

import styled from "styled-components";
...
export const StyledImage = styled.div`
	background-image: url("../../../static/images/image.png")
`

조치사항

이미지 파일을 import 한 변수를 url에 넣어준다.

import styled from "styled-components";
import tempImage from "../../../static/images/image.png"
...
export const StyledImage = styled.div`
	background-image: url(${tempImage})
`

추가

만약 Style-Component 파일을 따로 관리하고
이미지 import를 상위 파일에서 한다면
props로 import한 이미지를 Styled-Component로 넘겨 사용한다.

import tempImage from "../../../static/images/image.png"
...
<StyledImage path={tempImage}/>
export const StyledImage = styled.div`
	background-image: url(${(props) => { props.path })

그리고 import하는 것은 src 폴더 안에 있는 파일만 가능하다.

profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글