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

Frontend

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

패스트캠프 프론트앤드 인강 21일차 리액트에서 useRef로 컴포넌트안에 변수만들기와 배열에 항목추가하기를 배웠다.

 

컴포넌트안에 변수만들기

변수는 예를들어 컴포넌트 내부에 let키워드를 사용해 변수선언한다가정할때리랜더링될때 변수값은 초기화된다. 만약 계속유지하고싶으면 useState를 사용해야하는데 useState같은경우는 상태를 바꾸게되면 컴포넌트가 리랜더랑된다컴포넌트가 리랜더링될때마다 어떠한값을 관리할때도 useRef를 사용한다.

useRef로 관리하는 값은 바뀌어도 컴포넌트가 리랜더링되지않는다.

useRef의 활용

지난번에 사용했던 코드에 고유 id값을 useRef로 관리해보자.

App.js

import React, {useRef} from 'react';
import './App.css';
// import UserList from './UserList';
// import MultipleInput from './MultipleInput';
// import InputSample from './inputSample';
// import UseRef from './UseRef'
import UseRefasId from './UseRefasId'


function App() {
  //여기에 붙여넣고 import에 {useRef추가한다}
  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'}
  ]
  // 초기값을 4로한다.
  const nextId = useRef(4);
  const onCreate = () => {
    console.log(nextId.current); //4
    nextId.current += 1;
  }
  onCreate();
  return (
    // <InputSample/>
    // <MultipleInput/>
    // <UseRef/>
    // <UserList/>
    <UseRefasId food={food}/>

  );
}

export default App;

UseRefasId.js

import React from 'react';

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

export default function UserList({food}){
    //props로 받아온다 -> UserList에 파라미터값으로 들어가고 App.js로 이동
    // 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>
    )
}

요약하자면 ref는 특정DOM을 선택하고싶을때도 쓸수있지만 어떤 변수를 계속 기억하고싶을때(컴포넌트가 리랜더링되어도) 

ref를 변수로 관리하는것도 괜찮다라는것이다.

 

배열에 항목추가하기

새로운폴더를 만들고 4개의 props를 받아온다.

CreateFood.js

import React from 'react';

export default function CreateFood({foodname, ingredient, onChange, onCreate}){

    return (
        <div>
            <input name="foodname" placeholder="음식이름" onChange={onChange} value={foodname} />
            <input name="ingredient" placeholder="재료" onChange={onChange} value={ingredient} />
            <button onClick={onCreate}>등록</button>
        </div>
    )
    }

 

App.js에서 import하고 useState를 해서 여러개의 input값들을 관리해보자

useState로 감싸면 컴포넌트의 상태로 관리가된어 추출된다.

기존에 만들었던 배열이 현재 컴포넌트의 상태로서 관리가되어있지않은데 관리하도록하는방법은 

useState로 감싸주면된다.

import React, {useRef, useState} from 'react';
import './App.css';
import UseRefasId from './UseRefasId'
import CreateFood from './CreateFood'


function App() {
  const [inputs,setInputs] = useState({
    foodname:'',
    ingredient:'',
  });
  const {foodname, ingredient} = inputs;
  const onChange = e => {
    const {name, value} = e.target;
    setInputs({
      ...inputs,
      [name]:value
    })
  }
  //여기에 붙여넣고 import에 {useRef추가한다}
  //useState에 담으면 일반배열이 컴포넌트의 상태로써 관리된다.
  const [food, setFoods] = useState(
    [
    {id:'1', foodname:'pizza', ingredient:'cheese in topping with tomato and basil'},
    {id:'2', foodname:'pasta', ingredient:'pasta sauce,noodle,tomato sauce, meatball and basil'},
    {id:'3', foodname:'gambas', ingredient:'olive oil, shrimp, galic and pepper'}
    ]
  )

  // 초기값을 4로한다.
  const nextId = useRef(4);

  const onCreate = () => {
    const foods = {
      id: nextId.current,
      foodname,
      ingredient,
    };
    setFoods([...food, foods]);

    //입력될때 input 내용 지우기
    setInputs({
      foodname:'',
      ingredient:'',
    });

    // console.log(nextId.current); //4
    nextId.current += 1;
    console.log(nextId.current); //id값이 +1된모습을 확인할수있다.

  };
  // onCreate();
  return (
    <>
    <CreateFood foodname={foodname} ingredient={ingredient} onChange={onChange} onCreate={onCreate}/>
    <UseRefasId food={food} />
    </>
  )
}

export default App;

버거가 잘 추가된다.

기존의 배열은 건들지않으면서 새항목을추가하는 방법은 2가지가있다.

1.spread

    setFoods([...food, foods]);

2.concat

    setFoods(food.concat(foods));

spread말고 concat을 사용한모습.

https://bit.ly/31Cf1hp

 

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

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

www.fastcampus.co.kr

 

반응형