ReactJs to NextJs migration
Recently I purchase ReactJs template from market as I want to bypass UI coding. As you probably know that we can run React on NextJs framework but there is some difference. For example NextJs is server-side rendering but ReactJs render on client side so that you would experience compile failure.
I document what changes required when I transform my ReactJs template to NextJs project. Let get started.
Let create next project
and copy files to components and pages folder , correct import/asset path
<Link>
- Correct <Link> component. I use Webstrom so I can do it easily with Replace in Path (command + shift + R)
from
import { Link } from "react-router-dom";
to
import Link from 'next/link';
- Replace to= with href= as "href" is only required property for next/link
- Make sure that you wrap all child elements to single element under <Link>. For example ,
from
<Link> My text <span> is here</span>
to
<Link> My text is here </Link> or <Link><a>My text <span> is here</a></Link> or <Link><div>My text <span> is here</div></Link>
- <Link> in NextJs doesn't support className. So you need to move className to its child. For example
from
<Link .. className="xxx"><a>....</a></Link>
to
<Link...><a className="xxx"></a></Link>
NPM package
- The package that come with ReactJs project wouldn't work if it's client-side rendering. Some package has another version/branch for server-side rendering. For example react-owl-carousel is client-side rendering so that it works fine on ReactJs project. But to use in NextJs, you need react-owl-carousel2 or other components on your choicesd. I recommened to test new component on a test project before use it in your real project.
- Install next-images package, this make my life easier.
- Uninstall react-router-dom as we no longer use React Link
client-side Jquery
add client-side Jquery in _document.js
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
$document
$document is client side so you will get compile fail on NextJs project (NodeJs has no idea what $document is). To fix this issue wrap $document in useEffect() to make it be client-rendering mode
CSS file
NextJs support global stylesheet. Just define css file _app.js
import '../assets/css/App.css';
next.config.js
const withImages = require('next-images');
module.exports = withImages({
webpack: (config, {isServer, webpack}) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
if(isServer)
{
config.plugins.push(
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
)
}
// Important: return the modified config
return config
}
});
Nice article 👏