[React_Redux] Props

React passes data between components through States and Props. Let’s talk about Props first.

 

1. Props

Arguments passed to components are called props. They look just HTML attributes.
Props are read-only data that are passed from one component to another.

class AuthorList extends React.Component {
  render() {
   return ( 
     <div>
       <Author name="Ernest Hemingway" />
       <Author name="Stephen King" /> 
     </div>
   );
  };
}

Props are accessed using the “this.props” object in a class or an argument of a function.

class Author extends React.Component {
  render() {
   return ( 
     <p className="author-name">{this.props.name}</p>
   );
  };
}

 

2. Where to use Props

Props play 2 big roles:

  • Parent components send data to child components through props
  • Child components accept callback functions as props to communicate back with parent components

3. Passing Dynamic Data as Props

Let’s try a more real-world-like example.

getAuthors() {
  // call ajax and return this
  return [ 
    {id: 1, name: "Ernest Hemingway"}, 
    {id: 2, name: "Stephen King"} 
  ];
};

In the “AuthorList” component you can do like this.

getAuthorList() {
  let authorData = this.getAuthors();
  return authorData.map((author) => {
    return (
      <div key={author.id}>
        <Author name={author.name} />
      </div>
    );
  });
}

render() { 
 return (
     <div>{this.getAuthorList()}</div>
   );
  };

 

4. Rules

The react document says:
All React components must act like pure functions with respect to their props.

This means when the props are the same, the output of the component is always the same.
You should not modify the props inside the component.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s