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
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 tomy-website.render.com
, your rootindex.html
is loaded and everything works. But when you querymy-website.render.com/news
, the server tries to find the page atmy-website.render.com/news/index.html
, and there’s no HTML file there. And your rootindex.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.
in render dashbaord select static site.
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)
Add name and create app.
In the deployemnt go to
Redirects/Rewrites
section.now routes are working