thisisnotabus
thisisnotabus

Reputation: 2069

React Render Called Twice, Props Undefined on Second

The router (Director) calls Render on a parent component, which looks like this:

export class Parent extends React.Component {
  constructor(props) {
    super(props);
  } 


  render () {
    return <div className="content-section">
      <div className="content-header">Parent</div>
      <Child1 />
    </div>
  }
}

Child1 looks like this:

export class Child1 extends React.Component {
  constructor(props) {
    super(props);
  } 
  render() {
    let items = ['One', 'Two', 'Three'];
    console.log('ITEMS', items);
    return <div className="content-section">
      <Dropdown title="Test Title" items={items} />
    </div>;
  }
}

And then the dropdown component looks like this:

    class Dropdown extends React.Component {

      constructor(props) {
        super(props);
      } 
      render() {
         console.log('props', this.props.items);
         let items = [];
         this.props.items.forEach(item => items.push(<MenuItem key={item.id}>{item}</MenuItem>));
         return <div>
           <Dropdown title={this.props.title}>
           {items}
           </Dropdown>
         </div>
      }
   }

In the console, it is printing ITEMS once, correctly, and then PROPS twice, the first time correctly, the second time undefined. Obviously this is causing an error for me, as if it is undefined the forEach blows up. I don't understand what I've done wrong, as I'm just trying to pass an array from parent to child.

Upvotes: 1

Views: 2045

Answers (1)

Serhii Baraniuk
Serhii Baraniuk

Reputation: 3375

You're trying render Dropdown in Dropdown )

class Dropdown extends React.Component {

      constructor(props) {
        super(props);
      } 

      render() {
         console.log('props', this.props.items);
         let items = [];
         this.props.items.forEach(item => items.push(<MenuItem key={item.id}>{item}</MenuItem>));
         return <div>
           ------------- HERE!!!!
           <Dropdown title={this.props.title}>
           {items}
           </Dropdown>
         </div>
      }
   }

Look at this working example. I've created JSFiddle

Upvotes: 4

Related Questions