This is my server/server.js:
import express from "express";
import React from "react";
import ReactDOMServer, { renderToString } from 'react-dom/server';
import App from '../src/App';
const PORT = 4000;
const app = express();
app.use(express.static('./build', {index: false}));
app.get('/', (req, res) => {
const reactApp = renderToString(
<App/>
//<h2>Works using a simple h2</h2>
);
return res.send(
`
<html>
<body>
<div id="root">${reactApp}</div>
</body>
</html>
`
);
});
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
My server/index.js:
// server/index.js
require("ignore-styles");
require("@babel/register")({
ignore: [/(node_modules)/],
presets: ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"],
});
require("./server");
App.tsx:
import React from 'react';
import './App.css';
import Home from './components/Home/Home';
function App () {
return (
<div className="App">
<Home/>
</div>
);
}
export default App;
Finally, after I run the command:
node server/index.js
I got this error:
*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.
*
2
Answers
Can someone explain to me why this is a solution? Hand how can I keep my tsx files?
Changes:
in your server file, change the import to be
instead of
Because your App component is a default export, i.e.
export default App
, and not a named export, i.e.export { App }