skip to Main Content

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


  1. Chosen as BEST ANSWER

    Can someone explain to me why this is a solution? Hand how can I keep my tsx files?

    Changes:

    1. Change the name of the file from App.tsx to App.ts
    2. Remove and add a aimple h1 to try
    3. Comment the import of Home.tsx
    import React from 'react';
    import './App.css';
    //import Home from './components/Home/Home';
    
    function App () {
      return (
         <div className="App">
           //<Home/>
             <h1>Lets try this</h1>
         </div>
      );
    }
    
    export default App;
    

  2. in your server file, change the import to be

    import App from '../src/App';  // good
    

    instead of

    import {App} from '../src/App';  // bad
    

    Because your App component is a default export, i.e. export default App, and not a named export, i.e. export { App }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search