[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지20회차 미션
본문 바로가기

Frontend

[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지20회차 미션

패스트캠프 프론트앤드 인강 20일차 리액트에서 useRef로 특정 dom을 선택하는 방법과 배열랜더링을 배워보았다.

 

dom을 선택하는방법

1.useRef를 리액트에 import한다.

import React, {useRef} from 'react';

2.useRef() 함수를 호출한다.

const 유즈리프 = useRef();

3. 원하는 함수에 current.dom조정하는 코드를 넣어준다.

const 함수명 = () =>{
	유즈리프.current.focus();
}

4.사용할 태그에 useRef를 넣어준다.

<input ref={유즈리프}/>

 

활용예문(지난시간에 했던 inputSample.js를 다시불러서 해보았다.)

import React, {useState, useRef} from 'react'

export default function UseRef(){
        const nameInput = useRef();
        const [text, setText] = useState('');
        const onChange = (e) => {
            setText(e.target.value)
        }
        const onReset = () => {
            setText('');
            nameInput.current.focus();
        }
        return(
            <div>
                <input onChange={onChange} value={text} ref={nameInput}/>
                <button onClick={onReset}>초기화</button>
                <div>
                    <b>값</b>
                    {text}
                </div>
            </div>
        );
}

초기화뒤에 포커스가 이름태그에가있다.

배열랜더링

우선 아래의 비효율적인 코드를 배열랜더링을 통해 효율적으로 바꾸어보자

import React from 'react';

export default function UserList(){
    const food = [
        {name:'pizza', ingredient:'cheese in topping with tomato and basil'},
        {name:'pasta', ingredient:'pasta sauce,noodle,tomato sauce, meatball and basil'},
        {name:'gambas', ingredient:'olive oil, shrimp, galic and pepper'}
    ]
    return(
        <div>
            <div>
                <b>{food[0].name}</b> <span>{food[0].ingredient}</span>
            </div>
            <div>
                <b>{food[1].name}</b> <span>{food[1].ingredient}</span>
            </div>
            <div>
                <b>{food[2].name}</b> <span>{food[2].ingredient}</span>
            </div>
        </div>
    )
}

props를 활용한 컴포넌트를 추가해 비효율적인 코드중복을 줄여보자.

import React from 'react';

function User({foods}){
    return(            
    <div>
    <b>{foods.name}</b> <span>{foods.ingredient}</span>
    </div>
    );
}

export default function UserList(){
    const food = [
        {name:'pizza', ingredient:'cheese in topping with tomato and basil'},
        {name:'pasta', ingredient:'pasta sauce,noodle,tomato sauce, meatball and basil'},
        {name:'gambas', ingredient:'olive oil, shrimp, galic and pepper'}
    ]
    return(
        <div>
            <User foods={food[0]}/>
            <User foods={food[1]}/>
            <User foods={food[2]}/>
        </div>
    )
}

배열내장함수인 Map을 활용하면 더욱 효율적인 코드가 가능하다.

import React from 'react';

function Italian({foods}){
    return(            
    <div>
        <b>{foods.name}</b> <span>{foods.ingredient}</span>
    </div>
    );
}

export default function UserList(){
    const food = [
        {id:'1', name:'pizza', ingredient:'cheese in topping with tomato and basil'},
        {id:'2', name:'pasta', ingredient:'pasta sauce,noodle,tomato sauce, meatball and basil'},
        {id:'3', name:'gambas', ingredient:'olive oil, shrimp, galic and pepper'}
    ]
    return(
        <div>
            {food.map((test)=><Italian foods={test} key={test.id}/>)} 
        </div>
    )
}

여기서 key값이 들어가야 이러한 에러가안뜨는데

Warning: Each child in a list should have a unique "key" prop

key값은 index로 대체가능하지만 고유 id값을 이용하는게 좋다.

            {food.map((test,index)=><Italian foods={test} key={index}/>)} 

배열을 랜더링할때는 key를 넣어야 효율적인 없데이트가 가능(없으면 밀림현상)

 

실행결과

https://bit.ly/31Cf1hp

 

프론트엔드 개발 올인원 패키지 with React Online. | 패스트캠퍼스

성인 교육 서비스 기업, 패스트캠퍼스는 개인과 조직의 실질적인 '업(業)'의 성장을 돕고자 모든 종류의 교육 콘텐츠 서비스를 제공하는 대한민국 No. 1 교육 서비스 회사입니다.

www.fastcampus.co.kr

반응형