Search code examples
javascriptreactjsamplifyjs

Uncaught TypeError: this is undefined in Amplify UI in React


I installed Amplify Pagination to beautify my project, however, things got weird after I pasted code in my project, the console always shows

Uncaught TypeError: this is undefined

https://ui.docs.amplify.aws/components/pagination

I then created a default React project but the result remains the same.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { AmplifyProvider } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css'; // default theme

ReactDOM.render(
  <React.StrictMode>
    <AmplifyProvider>
      <App />
    </AmplifyProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

import { Pagination } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

function App() {
  return (
    <div className="App">
      <Pagination
      currentPage={1}
      totalPages={10}
      siblingCount={1}
      onChange={()=>this.onChange()}
      onNext={()=>this.onNext()}
      onPrevious={()=>this.onPrevious()}
    />

      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Solution

  • "this" is undefined because you are not in a class component

    function App() {
        const onChange = () => { do something }
        const onNext = () => { do something }
        const onPrevious = () => { do something }
          return (
            <div className="App">
              <Pagination
              currentPage={1}
              totalPages={10}
              siblingCount={1}
              onChange={onChange}
              onNext={onNext}
              onPrevious={onPrevious}
            />
        
              <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <p>
                  Edit <code>src/App.js</code> and save to reload.
                </p>
                <a
                  className="App-link"
                  href="https://reactjs.org"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  Learn React
                </a>
              </header>
            </div>
          );
        }
        
        export default App;