Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  57] [ 6]  / answers: 1 / hits: 8127  / 3 Years ago, tue, march 30, 2021, 12:00:00

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.


More From » reactjs

 Answers
5

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)

[#1558] Saturday, March 27, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;