Ben Aston
Ben Aston

Reputation: 55729

How does ReactJS prop binding work?

In the following a value (<ArticleList instance>.props.articles) is bound to a prop of HomePage (this.props.articles).

The object identity of this.props.articles might be undefined or it might change, so ReactJS must maintain "this.props.articles" as configuration instead of an object reference, permitting dynamic look-up.

Is this correct?

class HomePage extends React.PureComponent {
  render() {
    return <ArticleList articles={this.props.articles} />
  }
}

function ArticleList({articles}) { 
  if(!articles) return <div>There are no articles!</div>;
  return <div>{ articles.map(a => <Article value={a} />) }</div>;
}

Edit: I have edited the code to cover the case for undefined. My question remains.

To restate:

this.props.articles looks like a JavaScript expression to retrieve the value of a property.

But it cannot be for the reason stated in the question (you'd be binding undefined).

So is this instead special JSX syntax that JSX knows how to parse?

Upvotes: 0

Views: 58

Answers (1)

Fez Vrasta
Fez Vrasta

Reputation: 14815

Why are you saying that this.props.articles is not JavaScript?

Your code once transpiled by Babel becomes:

class HomePage extends React.PureComponent {
  render() {
    return React.createElement(ArticleList, {
      articles: this.props.articles,
    });
  }
}

function ArticleList({articles}) { 
  if(!articles) {
    return React.createElement('div', {}, 'There are no articles!');
  }
  return React.createElement('div', {},
    articles.map(a => <Article value={a} />)
  );
}

this.props.articles is simply a reference to the props property of the HomePage class.

Upvotes: 1

Related Questions