[ReactJS 이론] #2 Components and Props

mechaniccoder·2020년 5월 25일
0

ReactJS이론

목록 보기
2/4
post-thumbnail

내용

React component can be divided to many pieces and we can look into them individually. It is similiar to javascript function. It receive input called "props" and return React elements.

Function Component

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

ReactDOM.render(<Welcome name="sara" />, document.getElementById("root"));

We can set attributes in user define component and it is sent to component by "props" as a object argument. As above, we set attribute name="sara". So, it is transfered to Welcome() component as a "props" and the component return props.name.

Class Component

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

We have to divide and conquer the components!

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

We can simplify above code to below.

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>
  );
}

So, you should extract the common parts and make it component.

All react components have to act like a pure function when treating "props".

소감

영어를 공부하기 위해서 공식 docs를 영어로 정리해보고 있는데 어렵다... 그래도 꾸준히 노력할 것이다.

Reference

profile
세계 최고 수준을 향해 달려가는 개발자입니다.

0개의 댓글