How to render react as a client in express?

Viewed 30

I am new to react and I am trying to create an Express .ejs pages to serve React code on the same port. I am able to render ejs from the server but I am unable to connect to the react components. Any help would be appreciated :)

Here are the following files that I have:

website/app.js:

const express = require ('express');
const app = express();
app.set ('view engine', 'ejs');
app.use(express.static('public'));


app.get("/", function(req, res){
  res.render('portfolio')
});

website/views/portfolio.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <div class="container" >
        <h2>Server rendered EJS File</h2>
        <div id="main">
           <!--This div is where React Component Renders -->
        </div> 
    </div>
    <script type="module" src="portfoliomain.js"></script>
</body>
</html>

website/public/portfoliomain.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Portfolio from '../Components/PortfolioIndex';

const main = document.getElementById('main');
ReactDOM.hydrate(<Portfolio/>, main)

website/Components/PortfolioIndex:

import React from 'react'

function Portfolio() {
    return (
        <div className="react-stuff">
            <h1>My React App component</h1>            
        </div>
    )
}

export default Portfolio;
0 Answers
Related