0

I have big project build with React and react-router-dom and few days ago I started to use NextJS and I see that NextJS doesn't have some features that react-router-dom have so I wrote a component file that will do the missing features combine it with NextJS

Here is the file

import { useRouter } from 'next/router'
import Link from 'next/link'

const NavLink = ({ children, activeClassName, ...props }) => {
    const { asPath } = useRouter()
    const childClassName = props.className || ''

    // pages/index.js will be matched via props.href
    // pages/about.js will be matched via props.href
    // pages/[slug].js will be matched via props.as
    const { to, ...rest } = props;
    const className = asPath === props.to ? `${childClassName} ${activeClassName}`.trim() : childClassName

    return (
        <Link {...rest} href={to} passHref={true} className={className}><a>
            {children}
        </a></Link>
    )
}

export default NavLink

I'm wondering, how can I use this file as a package so I can avoid importing it locally.

I have a lot of nested components and its really wasting of time to do that

Like is there a way to use this file like this

import NavLink fron 'my-navlink';

Instead of

import NavLink fron '../.../components/public/ns/navlink.js';

Thank you

1 Answer 1

1

You can use Module path aliases :

just create a tsconfig.json or jsconfig.json file :

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@my-navlink": ["components/public/ns/navlink.js"]
    }
  }
}

And then anywhere in your pages/components you can import it :

import NavLink fron '@my-navlink';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Nico! You saved my time!!!! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.