[React] Component 합성과 추출

handa·2023년 9월 22일
0
post-thumbnail

1. Component 합성

Component 안에 또다른 Component를 쓸 수 있다.
복잡한 화면을 여러개의 Component로 나눠서 구현 가능!

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App(props) {
	return (
    	<div>
        	<Welcome name="Mike" />
        	<Welcome name="Steve" />
        	<Welcome name="Jane" />
       	</div>
    )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
	<React.StrictMode>
    	<App />
    </React.StrictMode>
);

2. Component 추출

큰 컴포넌트를 산산조각내자!
재사용성▲
개발속도▲

function Comment(props) {
	return (
    	<div className="comment">
        	<div className="user-info">
              	<img className="avatar"
                  	src={props.author.avatarUrl}
                  	alt={props.author.name}
                />
              	<div className="user-info-name">
                  	{props.author.name}
              	</div>
            <div>
              
            <div className="comment-text">
              	{props.text}
            </div>
              
            <div className="comment-data">
              {formatDate(props.date}}
            </div>
        </div>
    );
}

2-1. Avatar 추출하기

function Avatar(props) {
	return (
    	<img className = "avatar"
        	src={props.user.avatarUrl}
          	alt={props.user.name}
        />
    );
}
function Comment(props) {
	return (
    	<div className="comment">
        	<div className="user-info">
              	<Avatar user={props.author} />
              	<div className="user-info-name">
                  	{props.author.name}
              	</div>
            <div>
              
            <div className="comment-text">
              	{props.text}
            </div>
              
            <div className="comment-date">
              	{formatDate(props.date)}
            </div>
      	</div>
    );
}

2-2. UserInfo 추출하기

function UserInfo(props) {
 	return (
      	<div className="user-info">
        	<Avatar user={props.user} />
        	<div className="user-info-name">
              	{props.user.name}
        	</div>
        </div>
    );
}
function Comment(props) {
  	return (
      	<div className="comment">
        	<UserInfo user={props.author} />
        	<div className="comment-text">
              	{props.text}  
        	</div>
        	<div className="comment-date">
              	{formatDate(props.date)}
        	</div>
        </div>
    );
}

profile
진짜 해보자

0개의 댓글