I have 3 components in my React application that I use for Nav Bar. In each component, there is a div element with id = 'root'
Index.html
<div id="root"></div>
This is how it looks my App.js -
App.js
import logo from './logo.svg';
import './App.css';
import {Home} from './Home';
import {Department} from './Department';
import {Employee} from './Employee';
import {Navigation} from './Navigation';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div className="container">
<h3 className="m-3 d-flex justify-content-center">
React JS Tutorial
</h3>
<Navigation/>
<Routes>
<Route path='/' component={Home} exact/>
<Route path='/department' component={Department}/>
<Route path='/employee' component={Employee}/>
</Routes>
</div>
</BrowserRouter>
);
}
Example of Department Component:
Department.js
import React, {Component} from 'react';
export class Department extends Component{
render(){
return(
<div className="mt-5 d-flex justify-content-left">
This is Department page
</div>
)
}
}
This is my index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Home } from './Home';
//ReactDOM.render(React.createElement(App, null), document.getElementById('root'));
const root = ReactDOM.createRoot(
document.getElementById('root')
);
const element = <h1>Hello, world</h1>;
root.render(React.createElement(App, null), document.getElementsByClassName('root'));
I tried to use ReactDOM instead but without any success, this is how it looks
Update Solved
The problem was that I route by component instead element
Wrong <Route path='/department' component={Department}/>
Correct <Route path='/department' element={<Department/>}/>
Solved
The problem was that I route by component instead element
Wrong <Route path='/department' component={Department}/>
Correct <Route path='/department' element={<Department/>}/>
You are using getElementsByClassName
, but your div: <div id="root"></div>
does not have a property class="root"
use getElementById("root")
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.