I have a legacy PHP application and I'm trying to add server-side rendering using Next.js. I've followed the instructions on the Next.js documentation and created a pages directory for my Next.js application. However, I'm not sure how to go forward, the goal being that I inject next.js components or pages in different files of the php application.
Here's what I've done so far:
I've created a Next.js page at pages/Index.js that contains a simple component:
import { useEffect } from "react";
export default function HomePage() {
useEffect = () => {
console.log("Hello from Next.js");
};
return <div>Welcome to my Next.js homepage!</div>;
}
I've added the next dependency to my package.json file and added a script to watch for changes to my pages and components directories:
{
"dependencies": {
"next": "^12.1.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"scripts": {
"next": "nodemon --watch pages --watch components --exec 'next build'"
}
}
I've added a build configuration to my next.config.js file:
const { WebpackManifestPlugin } = require("webpack-manifest-plugin");
module.exports = {
distDir: "/output",
optimizeFonts: false,
webpack: (config, { isServer }) => {
config.plugins.push(
new WebpackManifestPlugin({
fileName: "manifest.json",
publicPath: "/output",
})
);
if (!isServer) {
config.devtool = "source-map";
}
config.optimization.minimize = false;
return config;
},
};
I've added a div element with the id of next_component to my PHP template:
<div id="next_component"></div>
In my parent PHP template, I've added a script tag that loads the latest build of my Next.js page:
<?php
$manifest = json_decode(file_get_contents(TL_ROOT . '/output/manifest.json'), true);
$latestBuild = $manifest['pages/Index.js'];
>
<script src="<?php echo $latestBuild; ?>"></script><!-- //! NEXT JS HERE -->
Finally, I've added a script to my Next.js page that mounts the component to the next_component element:
import "regenerator-runtime/runtime";
import { render } from "react-dom";
import HomePage from "./Index";
const ComponentToRender = (Component, element, reduxStore) => {
render(<Component {...element.dataset} />, element);
};
const element =
typeof window !== "undefined" && document.getElementById("next_component");
if (element) {
ComponentToRender(HomePage, element, false);
}
However, when I load my PHP page in the browser, the Next.js component doesn't seem to be rendering. What am I missing ?