skip to Main Content

I have a react app created with create-react-app how can deploy to render without having to write a server? Here is my code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import { BrowserRouter } from "react-router-dom";
import { AuthContextProvider } from "./AuthContext";
import './App.scss';
import './pages.scss';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <AuthContextProvider>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </AuthContextProvider>
);

Answers on deployment to Heroku are welcomed.

I tried to upload a react app to render.com, the project deployed successfully. But if I try to visit other paths likes "/news" and refresh the page, I get a blank screen with "Not Found" response.

2

Answers


  1. Libraries like react-router run on the client side. To handle a route with react-router, you need to load your entire application: the HTML page and the JavaScript bundle. Your JavaScript code will execute and handle the route.

    But the thing is, when you deploy your application, you only load the root index.html. When you make a request to my-website.render.com, your root index.html is loaded and everything works. But when you query my-website.render.com/news, the server tries to find the page at my-website.render.com/news/index.html, and there’s no HTML file there. And your root index.html with js bundle and react-router doesn’t even load.

    You need to configure the server to load your index.html on any route. So that the server at any address, for example, /news, gives your root index.html. Check out render.com documentation on how to set it up.

    Here is an article explaining this problem in detail using Github Pages and create-react-app as an example. The approach is the same for most static hosting.

    Login or Signup to reply.
  2. in render dashbaord select static site.

    dashboard

    1. then connect your github or add the public repository https url. https://github.com/dsmabulage/stackoverflow-cra.git (i created this repository to mock the react app)

    2. Add name and create app.

    3. In the deployemnt go to Redirects/Rewrites section.

    deploy

    1. Add this rule and save

    rule

    Source Path /*
    Destination Path    /index.html
    Action  Rewrite
    

    now routes are working

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