😍Phân biệt cách sử dụng useRouter, withRouter (ok)

useRouter sử dụng cho Function Element

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

withRouter có thể sử dụng cho Function Element, sử dụng cho Class Element

import { withRouter } from 'next/router'
function Page({ router }) {
  return <p>{router.pathname}</p>
}
export default withRouter(Page)
import React from 'react';
import { withRouter, NextRouter } from 'next/router';
interface WithRouterProps {
  router: NextRouter
}
interface MyComponentProps extends WithRouterProps {}
class MyComponent extends React.Component<MyComponentProps> {
  render() {
    return <p>{this.props.router.pathname}</p>
  }
}
export default withRouter(MyComponent)

Last updated

Was this helpful?