Norandir
Norandir

Reputation: 11

TypeError: Cannot read property 'bind' of undefined, I can not figure what this means. React js

I ran into this error when trying to run my React code and see it's a common error but after looking at other people's questions I am having issues still how to fix this. I am still new to React so I'm kinda lost. What the code is supposed to do is take a JSON file and and display it as a table and the button is supposed to then sort it by last name and redisplay the table.

import data from './data.json' //Imports the JSON from local file, can be changed later to pull from api
import {Button, View} from 'react-native';

export default function App() {

    return (
       <PaientTable/>
        
      );
}





class PaientTable extends React.Component { 
        

    constructor(props) {
        super(props);
        
        this.state = { counter: 0 };
       // this.sort = this.sort.bind(this);
      }
    
    
    render(){

        

       function sort (){ 
            return this.setState( 
  
              data.sort((a, b) => {//sorts by name
                  if (a.lName < b.lName) {
                    return -1;
                  }
                  if (a.lName > b.lName) {
                    return 1;
                  }
                  return 0;
                })
            );
        }
    return (

        
        
<table>
        <caption>Paients</caption>
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>
            <button type="button" onClick={() => this.sort.bind(this)}> 
              Last Name
            </button>
          </th>
            
          </tr>
        </thead>
        <tbody>
          {data.map(paient => (
            <tr>
              <td>{paient.id}</td>
              <td>{paient.fName}</td>
              <td>{paient.lName}</td>
            </tr>
          ))}
        </tbody>
      </table>
        
        
    
    );
          }
  }

Upvotes: 0

Views: 3624

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85211

You've defined sort to be a local variable inside of render, But all the places where you try to access it you're treating it as though its a member of the class. So instead of structuring it like this:

class PaientTable extends React.Component { 
 // ...
 render() {
    function sort () {
       // ...
    }
    // ...
 }
}

Do this:

class PaientTable extends React.Component { 
  // ...
  sort() {
    // ...
  }

  render() {
    // ...
  }
}

Upvotes: 3

Related Questions