본문 바로가기

Research/React40

useReducer는 다재다능한 훅 + 커스텀훅 useReducer는 다양한 상황에서 컴포넌트 상태를 업데이트 해줄 수 있는 hook으로, useState보다 좀 더 다재다능한 훅이라 생각하면 된다. useReducer는 첫 번째 파라미터에 reducer 함수를 두 번째 파라미터에 기본 값을 담은 객체를 넣어준다. import { useReducer } from 'react'; function reducer(state, action) { // action.type에 따라 다른 작업 수행 switch (action.type) { case 'INCREMENT': return { value: state.value + 1 }; case 'DECREMENT': return { value: state.value - 1 }; default: return state.. 2023. 10. 25.
useState로 여러 상태 관리하기 useState로 여러 상태 관리하기 import { useState } from 'react'; const Info = () => { const [name, setName] = useState(''); const [nickname, setNickname] = useState(''); const onChangeName = (e) => { setName(e.target.value); }; const onChangeNickname = (e) => { setNickname(e.target.value); }; return ( Name: {name} Nickname: {nickname} ); }; export default Info; 지금까지 책의 예제를 보면 onChangeXX 이벤트 발생 시, input창에만.. 2023. 10. 25.
React input 추가/삭제 기능 + 컴포넌트 반복 표현 const IterationSample = () => { const names = ['Jin', 'Paul', 'Law', 'Yosimitsu']; const nameList = names.map((name, index) => {name}); return {nameList}; }; export default IterationSample; This is the code to display list through iteration. Key is required so index from map function is passed. But using index is not perfect way. You should only use this way when there is unique value. Using ind.. 2023. 10. 24.
React 컴포넌트에 ref 달아서 스크롤 내리기 import { Component } from 'react'; import ScrollBox from './ScrollBox'; class App extends Component { render() { return ( (this.scrollBox = ref)} /> this.scrollBox.scrollToBottom()}> Go bottom.. ); } } export default App; import { Component } from 'react'; class ScrollBox extends Component { scrollToBottom = () => { const { scrollHeight, clientHeight } = this.box; this.box.scrollTop = scrollHeig.. 2023. 10. 24.