I have a working npm project and am trying to add a javascript file (App.js) to index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
App.js
import React, { Component } from 'react';
import './App.css'
class App extends Component {
render() {
return "Testing"
}
}
export default App;
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from './components/App';
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import {
Navigation,
Footer,
Home,
About
} from "./components";
ReactDOM.render(<App />,
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
<Footer />
</Router>,
document.getElementById("root")
);
serviceWorker.unregister();
I get the error, "Target container is not a DOM element". Other answers to this have said to put the div id="root" line in index.html at the end of the body which I have already done. If anyone can please help me figure out why I am getting this error, that would be very helpful. Thank you in advance.
CodePudding user response:
ReactDOM.render
expects 2 arguments: the component to render, and the parent element aka target. You give it 3 arguments.
You'll want to wrap what you have in a fragment or fix App
to actually be the wrapper.
ReactDOM.render(
<>
<App />
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
<Footer />
</Router>
</>,
document.getElementById("root")
);
or
class App extends Component {
render() {
return (<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
<Footer />
</Router>);
}
}
// ...
ReactDOM.render(
<App />,
document.getElementById("root")
);