ReactJS - ref undefined

- 1 answer

Ad

I moved away from Alt to Redux and decided to take advantage of context type. Somewhere in the mix, my ref is now undefined.

What would be the proper procedure for refs to be available with this code:

import React, { Component, PropTypes } from 'react';
// components
import TopNavMenuItem from './top-nav-menu-item';

export default class TopNavZone extends Component {

   fetchMenu() {
     const results = [];
     const navItems = this.context.navItems;
     navItems.map((item, index) => {
       results.push(
         <TopNavMenuItem key={ index }
           clientId={ this.context.clientInfo._id }
           item={ item }
           index={ index }
           parent={ this.refs.topNavList }
         />
      );
     });
     return results;
   }

  render() {
    return (
      <section>
        <nav className="top-nav" id="TopNavZone">
          <ul ref="topNavList" className="">
            { this.fetchMenu() }
          </ul>
        </nav>
      </section>
    );
  }
}

TopNavZone.contextTypes = {
  navItems: PropTypes.array.isRequired,
  clientInfo: PropTypes.object.isRequired
};

Thank you all.

Ad

Answer

Ad

I captured the ref in ComponentDidMount and made the data part of state instead of calling the function this.fetchMenu from render:

import React, { Component, PropTypes } from 'react';
// components
import TopNavMenuItem from './top-nav-menu-item';

export default class TopNavZone extends Component {

  constructor(props) {
    super(props); {
      this.state = {
        results: null
      }
    }
  }

  componentDidMount() {
    var topNavList = this.refs.topNavList;
    this.setState({ results: this.fetchMenu(topNavList) })
  }

  fetchMenu(topNavList) {
    const results = [];
    const items = this.context.navItems;
    items.map((item, index) => {
      results.push(
        <TopNavMenuItem key={ index }
                        clientId={ this.context.clientInfo._id }
                        item={ item }
                        index={ index }
                        parent={ topNavList }
        />
      );
    });
    return results;
  }

  render() {
    return (
      <section>
        <nav className="top-nav" id="TopNavZone">
          <ul ref="topNavList" className="">
            { this.state.results }
          </ul>
        </nav>
      </section>
    );
  }
}

TopNavZone.contextTypes = {
  navItems: PropTypes.array.isRequired,
  clientInfo: PropTypes.object.isRequired
};
Ad
source: stackoverflow.com
Ad