리액트 이미지 삽입 방법 from Public Folder

Sujeong Ji·2022년 8월 15일
0

React

목록 보기
9/9
post-thumbnail

Styles and Assets : Using the Public Folder

There is a special page about the /public folder in the official documentation:

https://create-react-app.dev/docs/using-the-public-folder/


If you put a file into the public folder, it will not be processed by webpack. Instead it will be copied into the build folder untouched. To reference assets in the public folder, you need to use an environment variable called PUBLIC_URL.

1. Inside index.html, you can use it like this:

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
or

Only files inside the public folder will be accessible by %PUBLIC_URL% prefix. If you need to use a file from src or node_modules, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build.

When you run npm run build, Create React App will substitute %PUBLIC_URL% with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL.

2. In JavaScript code, you can use process.env.PUBLIC_URL for similar purposes:

render() {
  return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}

3. Inline-style CSS

You can't use those solution in a CSS file. So you'll have to precise the ressource from the JS files:

const MyComp = () => {
  return <div style={{ backgroundImage: "url(/images/login-bg.jpg)" }}/>;
}
 const homepageImage = {
    backgroundImage: `linear-gradient(
      rgba(255, 255, 255, 0.5),
      rgba(255, 255, 255, 0.1)
      ), url("/images/login-bg.jpg")`,
  };

  return (
    <div className="app" style={homepageImage}>

< Reference >

profile
Studying Front-end Development 🌼

0개의 댓글