우사미 코딩

[React] css파일 불러오고 적용하기 본문

React

[React] css파일 불러오고 적용하기

맑은 눈의 우사미 2023. 6. 23. 15:59
반응형

 후.. 드디어왔다 css 

css는 잘 몰라서 좀 길게 씀

 

 

1. src에 css파일을 생성한다

css파일은 하나에 다 정의해두어도 되지만 그러면.. 나중에 디버깅.. 네..

그렇기 때문에 파일을 나누겠습니다

 

1. App에 스타일주기 

1) App.js

    import './App.css';
    import AnimalShow from "./AnimapShow";
    import { useState } from "react";
    function getRandomAnimal(){
        const animals = ['bird','cat','cow','dog','gator', 'horse'];

        return animals[Math.floor(Math.random() * animals.length)]; 
    }
    function App(){    
        const[animals, setAnimals] = useState([]);
        const handleClick = () =>{
            setAnimals([...animals, getRandomAnimal()]);
        }
        const renderAnimals = animals.map((animal, index) => {
            return <AnimalShow type = {animal} key={index}/>
        });
        return (
            <div className="app">
                <button onClick={handleClick}>Add animal</button>            
                <div className='animal-list'>{renderAnimals}</div>
            </div>
        );
    }
    export default App;

1행에 보면 App.css를 저렇게 불러오고

 App()함수 안에서 가장 ㅂ ㅏ깥에 있는 div에 "app"이라는 클래스를 추가했고

동물 리스트를 띄워줄 div에는 "animal-list"라는 클래스를 추가했습니당

 

2) App.css

    .app{
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    button{
        background-color: lightgreen;
        border:1px solid green;
        border-radius: 3px;
        font-size : 20px;
        padding: 10px;
        width : 30%;
    }

    .animal-list{
        display: flex;
        flex-direction: row;
        flex-wrap : wrap;
        justify-content: center;
    }

app 클래스에만 스타일을 줬을때는

[버튼]
[이미지]
[이미지]
[이미지]

이렇게 column으로 나열이 되고 (display : flex 와 flex-direction : column에 의해)

가운데 정렬이 된 상태이다 (align-items : center에 의해)

app에만 스타일 적용

이제 animal-list에도 스타일을주면

[버튼]
[이미지][이미지][이미지]

리스트는 가로로 나열된다 (display : flex 와 flex-direction : row에 의해)

flex-wrap : wrap으로 하면 이미지가 화면에 꽉 찼을때 자동 줄바꿈을 하고

이걸 주석하면 줄바꿈없이 옆으로 확장하면서 가로스크롤이 길어진다

justify-content는 컨테이너 내부 아이템들의 주 축 정렬을 어떻게 할 것인가인데 가운데로 맞춰주면 보기 좋게 가운데에 나온다.

animal-list까지 스타일을 적용

 

 

 

2. AnimalShow에 css적용하기

1) AnimalShow.js

    import './AnimalShow.css'
    import bird from './svg/bird.svg';
    import cat from './svg/cat.svg';
    import dog from './svg/dog.svg';
    import horse from './svg/horse.svg';
    import gator from './svg/gator.svg';
    import cow from './svg/cow.svg';
    import heart from './svg/heart.svg';
    import { useState } from 'react';

    const svgMap = {
        bird,cat,dog,horse,gator,cow
    }
    function AnimalShow({type}){
        const [clicks, setCliks] = useState(0);
        const handleClick=()=>{
            setCliks(clicks+1);
        };
        return (
            <div className='animal-show' onClick={handleClick}>
                <img className='animal' alt="animal" src={svgMap[type]} />
                <img 
                    className='heart'
                    alt="heart" 
                    src={heart}
                    style={{width: 10+10 * clicks + 'px'}}
                />
            </div>
        );
    }
    export default AnimalShow;

여기서는 동물이미지를 클릭하면 하트이미지가 커지도록

state를 사용하여 clicks변수와 setter를 정의하고 onClick이벤트를 넣었다

 

 

2) AnimalShow.css

    .animal-show{
        position: relative;
        border: 1px solid lightgray;
        padding: 10px;
        border-radius: 5px;
        margin: 10px;
        box-shadow: 0px 3px 4px lightgray;
    }

    .animal{
        height: 200px;
        width: 200px;
    }
    .heart{
        position:absolute;
        bottom: 10%;
        right:10%;
    }

 

-결과

 

반응형

'React' 카테고리의 다른 글

[React] event, eventHandler, callbackFunction  (0) 2023.06.25
[React] Axios, API  (0) 2023.06.25
[React] map  (0) 2023.06.23
[React] state - 배열 초기화, 새로운 요소 추가하기  (0) 2023.06.23
[React] state 사용하기  (0) 2023.06.23
Comments