'Can't render multiple components in the same page In React 18.1.0 version
I want to render both NavBar and Counters components in the same page. But when the applications always shows only the index element. I want to get both navigation bar and the counter component in my index page. As I am new to React could somebody help me to solve this matter?
App.js
import './App.css';
import Counter from './components/counter';
import Counters from './components/counters';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
import NavBar from './components/navbar';
function App() {
return (
<Router className="App">
<Routes>
<Route index element={<Counters/>}/>
<Route component={<Counters/>}/>
</Routes>
</Router>
);
}
export default App;
navbar.jsx
import React, { Component } from 'react'
import 'bootstrap/dist/css/bootstrap.css'
class NavBar extends Component {
state = { }
render() {
return(
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="./counter.jsx">Navbar</a>
</nav>
);
}
}
export default NavBar;
counters.jsx
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css'
class Counter extends Component {
state = {
value:this.props.value,
tags:[
"tag1",
"tag2",
"tag3"
]
} ;
incrementHandle=()=>{
this.setState({value: this.state.value+1})
};
render() {
return (
<div>
<span className='badge badge-primary m-2'>{this.formatCount()}</span>
<button onClick={this.incrementHandle} className='btn btn-seconday btn-sm'>Increment</button>
<button onClick={this.props.onDelete} className="btn btn-danger btn-sm m-2">Delete</button>
<ul>
{this.state.tags.map(tag=>
<li key={tag.id}>{tag}</li>)}
</ul>
</div>);
}
formatCount(){
const {value} = this.state;
return value === 0 ? "Zero" :value;
}
}
export default Counter;
This is my code.
Solution 1:[1]
Route only loads only one component, You can add NavBar on top of the router, It'll always be visible.
Better way is create HOC and wrap if you have case like before auth and after auth.
function App() {
return (
<>
<NavBar />
<Router className="App">
<Routes>
<Route index element={<Counters />} />
<Route component={<Counters />} />
</Routes>
</Router>
</>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul Sharma |
