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>
);
}
}
sortfunction is inside therenderfunction. Move that outside. Next, you only need to "bindthis" in your constructor. Uncomment the line you've got in your constructor. Lastly, since you don't need to bind inside therenderfunction, change your button'sonClicktoonClick={this.sort}. There's some more information about bindingthisfor events such as change events and why it's necessary here: reactjs.org/docs/handling-events.html