Reputation: 35
I am learning react and the course I am learning from uses a previous version of react. The tutor calls routing
inside ReactDom.render()
. I am not able to figure out how to get it to work inside root.render()
. i end up getting a blank page instead of App component.
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import { Route, Link, Switch, BrowserRouter as Router } from "react-router-dom";
import "./index.css";
import App from "./App";
const routing = (
<Router>
<Route path="/" component={App} />
</Router>
);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<h1>{routing}</h1>
</React.StrictMode>
);
App.js
import React from "react";
const App = () => {
return (
<div>
<h1>App component</h1>
</div>
);
};
export default App;
Upvotes: 1
Views: 100
Reputation: 1248
Applies to React Router v6:
You need to wrap <App />
with the <Router />
component
Delete the const routing: ...
and do this instead:
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
Now in your app component wrap the component you want to render with a specific route in <Routes />
:
import React from "react";
import { Routes, Route } from "react-router-dom";
const App = () => {
return (
<Routes>
<Route path="/" element={<ANY_COMPONENT_YOU_WANT/>} />
</Routes>
);
};
export default App;
Upvotes: 1