우사미 코딩

[React] 프로젝트에 이미지 추가하고 불러오기 본문

React

[React] 프로젝트에 이미지 추가하고 불러오기

맑은 눈의 우사미 2023. 6. 22. 13:40
반응형

1. src폴더안에 images 폴더 생성 후 이미지파일 넣는다

 

2. 이미지를 import한다 (App.js)

    import ProfileCard from "./ProfileCard";
    import AlexaImage from "./images/alexa.png";
    import CortanaImage from "./images/cortana.png";
    import SiriImage from "./images/siri.png";

    console.log(AlexaImage);
    console.log(SiriImage);
    function App(){
        return(
            <div>
                <div>Personal Digital Assistance</div>
                <ProfileCard title = "Alexa" handle="@alexa123" image={AlexaImage}/>
                <ProfileCard title = "Cortana" handle="@cortana32" image={CortanaImage}/>
                <ProfileCard title = "Siri" handle="@siri01" image={SiriImage}/>
            </div>
        );
    }

    export default App;

이미지는 컴포넌트처럼 변수로 선언하여 사용할 수 있다.

import 한 후 컴포넌트의 props로 넘겨준다

 

console.log로 찍으면 용량이 작은건 base64형식으로 출력되고

용량이 크면 서버에서 처리되는 경로를 출력한다

이런식으로 말이져

 

 

3. ProfileCard.js

    function ProfileCard({title, handle, image}){
        return (
            <div>            
                <img src={image}/>
                <div>Title is {title}</div>
                <div>Handle is {handle}</div>                        
            </div>
        );
    }
    export default ProfileCard;

부모컴포넌트에서 props로 넘겨진 image를 출력하기 위해서 인자를 수정했고 img태그를 추가했다.

 

 

브라우저에서 개발자 도구를 켜도 아무런 에러가 없지만

터미널을 보면

warning 파티 ^^

읽어보니 img태그에 alt 속성을 추가해달라고 한다.

어렵지 않은 요청이니 alt="pda logo"이런식으로 추가해준다.

 

 

반응형
Comments