0

I'm a beginner when it comes to ReactJS and ES6, and I'm writing my first web app to get a basic understanding, but I'm having issues passing a function from a ReactJS component to a stateless functional component.

The error message I get is this:

Uncaught TypeError: Cannot read property 'click' of undefined

The source code for the component is below:

import React, { Component } from 'react';
import firebase from 'firebase';

class SearchList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      professionals: []
    }

    this.click = this.click.bind(this);
  }

  componentDidMount() {
    console.log("componentDidMount");
    const dbRef = firebase.database().ref("Professionals/");
    dbRef.on("child_added", (snapshot) => {
      const professional = snapshot.val();
      professional.key = snapshot.key;
      const newProfessionals = this.state.professionals;
      newProfessionals.push(professional);
      this.setState({
        professionals: newProfessionals
      });
    });
  }

  render() {
    return (
      <ul>
        {this.state.professionals.map(function(professional) {
          return (
            <Item
              name={professional.companyName}
              deleteHandler={this.click}
              key={professional.key} />
          )
        })}
      </ul>
    );
  }

  click(key) {
    console.log("Deleting professional with key " + key + "...");
  }
}

var Item = function(props) {
  return (
    <li>
      {props.name} <button onClick={props.deleteHandler}>x</button>
    </li>
  )
}

export default SearchList;

If I comment out the line with deleteHandler={this.click} in the render function, I get no warnings, but then also nothing happens when I click, obviously.

As you might tell, the web app is connected to a realtime database over at Firebase. The connection to the database works perfectly fine and the array is populated as expected.

Bonus question:

When passing the function to the stateless functional component, should I include the parameter (in this case, the professional.key), or should the stateless functional component send that itself?

Tips and tricks as well as best practices are welcome. :)

Göran Lilja
  • 625
  • 2
  • 5
  • 17
  • 3
    Set `this` from `.map` callback - `this.state.professionals.map(function(professional) {}, this);`, or use arrow function `this.state.professionals.map((professional) => { });` – Oleksandr T. Nov 28 '16 at 16:42
  • 1
    @AlexanderT. wow that was quick. And it also does the trick. Add it as a response and I'll mark it as "answered". :) – Göran Lilja Nov 28 '16 at 16:45
  • Well, I might have been too excited, but at least it helped me out partly. – Göran Lilja Nov 28 '16 at 16:56

0 Answers0