2

I've got a react function and in the render method I am trying to have a method run 'onClick'.

let categories_list=this.state.categories.results.map(function(category){
        return (
          <a onClick={() => this.getNewUrl(category_id)}>
            <li key={category.id}>
            ID: {category.id}<br/>
            Title: {category.name}<br/>
            Organisation: {category.organisation}<br/>
            </li>
        </a>
       )});

And this is the function that I am trying to run:

getNewUrl(category_id) {
  this.setState((prevState, props) => ({
    assessments_List_url: "/api/assessments/?by-category=" + category_id + "/"
  }))
  console.log('yo ik draai')
 };

Both are in the same component and for good measure I also explicitly bound the function in the components constructor method.

this.getNewUrl = this.getNewUrl.bind(this);

Yet when I run this code and click the corresponding tag I get the following error.

Uncaught TypeError: Cannot read property 'getNewUrl' of undefined

Does anyone have an idea of what I am doing wrong? I've stuck pretty close to the examples in the react documentation, so I am really at a loss of what I am doing wrong.

Jasper
  • 2,131
  • 6
  • 29
  • 61

3 Answers3

1
const that = this;

let categories_list=that.state.categories.results.map((category) => {
    return (
        <a onClick={() => that.getNewUrl(category_id)}>
            <li key={category.id}>
                ID: {category.id}<br/>
                Title: {category.name}<br/>
                Organisation: {category.organisation}<br/>
            </li>
        </a>
    );
});

Make this an arrow function to get context of this. (If you haven't already bound this to this function.)

 getNewUrl = (category_id) => {
      this.setState((prevState, props) => ({
        assessments_List_url: "/api/assessments/?by-category=" + category_id + "/"
      }))
      console.log('yo ik draai')
     };
Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
1

Use arrow function here:

let categories_list=this.state.categories.results.map((category) => { // <== !!!
        return (
          <a onClick={() => this.getNewUrl(category_id)}>
            <li key={category.id}>
            ID: {category.id}<br/>
            Title: {category.name}<br/>
            Organisation: {category.organisation}<br/>
            </li>
        </a>
       )});

When you use function syntax this keyword refers to the object the function belongs to. Not to your react component.

Mikhail Shabrikov
  • 8,453
  • 1
  • 28
  • 35
1

Please try binding that anonymous function , might help

let categories_list=this.state.categories.results.map(function(category){
    return (
      <a onClick={() => this.getNewUrl(category_id)}>
        <li key={category.id}>
        ID: {category.id}<br/>
        Title: {category.name}<br/>
        Organisation: {category.organisation}<br/>
        </li>
    </a>
   )}.bind(this));
Jeffin
  • 1,099
  • 12
  • 23