-1

My project is built on ReactJS class components. I don't know NextJS and unfortunately i am not good at react-router too. However, i tried something.

import React, { Component } from 'react';
import useRouter from 'next/router';

    class App extends Component {
    
        Router = useRouter()

        render() {
        return <div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
             <button  onClick={() => Router.push('https://www.google.com/')}> Join </button>
          </div>
        </div>
      }
    }
    
    export default App;

I know it is wrong, therefore getting an error. Here I only want to redirect to google home page after clicking on button. Kindly help.

John V
  • 7
  • 2
  • 5
  • What error are you getting? – juliomalves Oct 04 '21 at 14:34
  • React Hook "useRouter" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function – John V Oct 04 '21 at 14:46
  • Does this answer your question? [How to use "useRouter()" from next.js in a class component?](https://stackoverflow.com/questions/57027469/how-to-use-userouter-from-next-js-in-a-class-component) – juliomalves Oct 04 '21 at 14:46
  • no, it doesn't. I am asking a small concept for a large live project which comprises 100+ components. – John V Oct 04 '21 at 14:50
  • The error you mentioned references `useRouter` but that's nowhere in the code you've posted. Could you provide an actual [mre]? – juliomalves Oct 04 '21 at 15:05
  • edited the code – John V Oct 04 '21 at 15:34
  • As exemplified in the link I posted above: 1) Import `import { withRouter } from 'next/router';`; 2) Wrap the `App` component with `withRouter`, i.e. `export default withRouter(App)`; 3) Access the router with `this.props.router.push('https://www.google.com/')`. Also makes sure to remove `Router = useRouter()`. – juliomalves Oct 04 '21 at 15:41

1 Answers1

0

you import built-in next router like this:

import {useRouter} from 'next/router'

// const router = useRouter() - inside a componenet

then you do:

router.push('...')

Edit

By the way, why you don't just use <a href='google.com'>Google</a>?

A.Anvarbekov
  • 955
  • 1
  • 7
  • 21