한 걸음씩
[React]Thinking in React: components, composition, and reusability 본문
React
[React]Thinking in React: components, composition, and reusability
winter17 2024. 1. 22. 17:24
# exercise 1: Create the stars
export default function App() {
return (
<div>
<StarRating maxRating={5} />
</div>
)
}
function StarRating({ maxRating = 5 }) {
const [rating, setRating] = useState(1)
const [tempRating, setTempRating] = useState(0)
function handleRating(rating) {
setRating(rating)
}
return (
<div style={containerStyle}>
<div style={starContainerStyle}>
{Array.from({ length: maxRating }, (_, i) => (
<Star
key={i}
full={tempRating ? tempRating >= i + 1 : rating >= i + 1}
onRate={() => handleRating(i + 1)}
onHoverIn={() => setTempRating(i + 1)}
onHoverOut={() => setTempRating(0)}
/>
))}
</div>
<p style={textStyle}>{tempRating || rating || ''}</p>
</div>
)
}
수동으로 별을 생성하기보다 Array.from을 사용하여 능동적으로 별을 생성할 수 있도록 구현
full은 hover상태와 마우스를 눌렀을 때 상태를 체크하는데
tempRating은 별 위에 마우스가 올라간 상태를 뜻하고 tempRating가 존재하면 별을 hover상태에서 채워준다.
onRate는 handleRating함수를 실행시켜 rating의 값을 변경한다.
onHoverIn은 hover상태인 tempRating 값을 변경한다.
onHoverOut은 tempRating 값을 0으로 만들어 까만 별이 하나인 상태로 만든다. (초기화)
function Star({ onRate, full, onHoverIn, onHoverOut }) {
return (
<div
role="button"
style={starStyle}
onClick={onRate}
onMouseEnter={onHoverIn}
onMouseLeave={onHoverOut}
>
{full ? '★' : '☆'}
</div>
)
}
StarRating함수에서 받아온 props를 onClick, onMouseEnter, onMouseLeave 속성으로 값을 전하여 화면을 랜더링 한다.
# challenge: Text Expander Component
export default function App() {
return (
<div>
<TextExpander className="box">
Space travel is the ultimate adventure! Imagine soaring past the stars
and exploring new worlds. It's the stuff of dreams and science fiction,
but believe it or not, space travel is a real thing. Humans and robots
are constantly venturing out into the cosmos to uncover its secrets and
push the boundaries of what's possible.
</TextExpander>
<TextExpander
collapsedNumWords={20}
expandButtonText="Show text"
collapseButtonText="Collapse text"
buttonColor="#ff6622"
className="box"
>
Space travel requires some seriously amazing technology and
collaboration between countries, private companies, and international
space organizations. And while it's not always easy (or cheap), the
results are out of this world. Think about the first time humans stepped
foot on the moon or when rovers were sent to roam around on Mars.
</TextExpander>
<TextExpander expanded={true} className="box">
Space missions have given us incredible insights into our universe and
have inspired future generations to keep reaching for the stars. Space
travel is a pretty cool thing to think about. Who knows what we'll
discover next!
</TextExpander>
</div>
)
}
function TextExpander({
collapsedNumWords = 10,
expandButtonText = 'Show more',
collapseButtonText = 'Show less',
buttonColor = 'blue',
expanded = false,
className,
children,
}) {
const [isExpanded, setIsExpanded] = useState(expanded)
const displayText = isExpanded
? children
: children.split(' ').slice(0, collapsedNumWords).join(' ') + '...'
const buttonStyle = {
background: 'none',
border: 'none',
font: 'inherit',
cursor: 'pointer',
marginLeft: '6px',
color: buttonColor,
}
return (
<div className={className}>
<span>{displayText}</span>
<button onClick={() => setIsExpanded(exp => !exp)} style={buttonStyle}>
{isExpanded ? collapseButtonText : expandButtonText}
</button>
</div>
)
}
부모 컴포넌트로부터 받은 props들의 기본값을 지정한 후
useState 상태 값을 이용하여 텍스트가 확장되었을때, 축소되었을 때에 따라 보이는 것을 달리한다.
★ prop-types
React 컴포넌트에서 프로퍼티의 타입을 정의하고 검사하기 위한 도구이다. 주로 개발 중에 발생할 수 있는 프로퍼티 관련 오류를 사전에 방지하기 위해 사용된다. 작은 프로젝트에서는 선택 사항일 수 있으나, 프로젝트의 규모가 커질수록 prop-types를사용하는 것이 좋다.
- 타입 검사 및 버그 방지
- 문서화와 가독성 향상
- 버전 업그레이드와 유지보수
- 런타임 오류 방지
- 코드 에디터의 지원
// npm install --save prop-types
import PropTypes from 'prop-types'
TextExpander.propTypes = {
collapsedNumWords: PropTypes.number,
expandButtonText: PropTypes.string,
collapseButtonText: PropTypes.string,
buttonColor: PropTypes.string,
expanded: PropTypes.bool,
className: PropTypes.string,
children: PropTypes.string.isRequired,
}
'React' 카테고리의 다른 글
[React] How React works (0) | 2024.01.26 |
---|---|
[React] How react works behind the scenes (0) | 2024.01.26 |
[React] TodoList - 추가, 삭제, 정렬 (0) | 2024.01.17 |
[React] React mini project2 - travel-list (1) | 2024.01.16 |
[React] state management (0) | 2024.01.15 |