I am relatively new to React and can't for the life of me figure out why this isn't working!
This code is not loading the App component inside router, but it does when returned independently. Example below
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { Router, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<Router>
<Route path="/">
<App />
</Route>
</Router>,
document.body.appendChild(document.createElement("div"))
);
});
Nothing loads on the screen with this. However when I remove the router I see the App component load:
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { Router, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<App />,
// <Router>
// <Route path="/">
// <App />
// </Route>
// </Router>,
document.body.appendChild(document.createElement("div"))
);
});
Finally, this is my App component (dont think you need this though)
import React from "react";
const App = () => {
return <div>app has loaded</div>;
};
export default App;
This is built on a Ruby on Rails app, if that matters
CodePudding user response:
Instead of
import { Router, Route } from "react-router-dom";
try
import { BrowserRouter, Route } from "react-router-dom";
CodePudding user response:
What versions of react and react-router-dom are you using? This works for me in a fresh npx create-react-app
:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, Routes, Route } from "react-router-dom"; // BrowserRouter as Router
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
</Routes>
</BrowserRouter>
</div>,
document.body.appendChild(document.createElement("div"))
);
});