My app has a simple routing with ssr and below is my code
index.tsx
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.min.css";
ReactDOM.hydrate(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
serviceWorker.unregister();
App.tsx
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import Home from "./components/home/Home";
import Tournament from "./components/tournament/Tournament";
import "./App.css";
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/" exact strict component={Home} />
<Route
path="/tournament/:tourId/:tourName"
exact
component={Tournament}
/>
<Redirect from="*" to={"/"} />
</Switch>
</Router>
</div>
);
}
export default App;
server/server.js
import path from "path";
import fs from "fs";
import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";
import App from "../src/App";
const PORT = 8000;
const app = express();
const router = express.Router();
app.get("/*", (req, res) => {
const context = {};
const app = ReactDOMServer.renderToString(
<App />
);
const indexFile = path.resolve("./build/index.html");
fs.readFile(indexFile, "utf8", (err, data) => {
if (err) {
console.error("Something went wrong:", err);
return res.status(500).send("Oops, better luck next time!");
}
return res.send(
data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
);
});
});
router.use(
express.static(path.resolve(__dirname, "..", "build"), { maxAge: "30d" })
);
// tell the app to use the above rules
app.use(router);
app.use(express.static("./build"));
app.listen(PORT, () => {
console.log(`SSR running on port ${PORT}`);
});
server/index.js
require("ignore-styles");
require("@babel/register")({
ignore: [/(node_modules)/],
presets: ["@babel/preset-env", "@babel/preset-react"],
});
require("./server");
When I run node server/index.js it starts the server which is fine. But when I lauch the http://localhost:8000/ on browser, it gives me the below error
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. at ReactDOMServerRenderer.render ...
PS: I am new to reactjs