'using react router with next.js

I am learning how to use Next.js/React for my application. I am currently researching the topic of routing and I had a few questions. I know that you can use react-router for React (I used vue-router before). However, I do not know if I need to use react-router with Next.js and how I would use it if I could. I am currently using a pages directory to hold pages to redirect to. How can I redirect to different pages in React/Next?

Here is some sample code to implement it in:

Class Login extends Component {

  state = {
    user: {},
  }

  loginUser = (e) => {
      loginUser(this.state.user)
        .then(response => {
          console.log(response);
          if (response['username']) {
            console.log('yippee!');
          }
      });
  }

}

After yippee, I want to redirect to /home which is in the pages folder.



Solution 1:[1]

For your first question I need to say: No, you don't need react-router in Nextjs it will use something called file-system based router which you can read more about it here

So after you set up your routes if you want to Navigate to them you have two options:

first using the Link Component from next/link: more about it here

second using the router from next/router which you can Navigate around like useHistory from react-router: more about it here

example from the doc:

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.asPath === href ? 'red' : 'black',
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink

So in your case, using this is how you can redirect:

import { withRouter } from 'next/router'

Class Login extends Component {

  state = {
    user: {},
  }

  loginUser = (e) => {
      loginUser(this.state.user)
        .then(response => {
          console.log(response);
          if (response['username']) {
            console.log('yippee!');
            //here is what you need:
            this.props.router.push('/your-route');
          }
      });
  }

}

export default withRouter(Login)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1