Reputation: 21
I am new to React.js and i am having a problem in routing the components. I have 2 different blogs and both blogs have different header and footer. What is the best way to to render different header and footer for certain pages like Article and Home Screen. I have tried making separate layouts and use Routing in those layouts and then used it in my App.js but it's not working
I have done the following things but nothing working for me:
My Simple_Blog.js file is:
class Simple_Blog extends Component {
render() {
return (
<>
<SimpleHeader />
<Routes>
<Route exact path="/" element={<LaunchScreen/>}/>
<Route exact path="/article1" element={<Article1/>}/>
</Routes>
<SimpleFooter />
</>
);
}
}
export default Simple_Blog
My Mega_Blog.js file is:
class Mega_Blog extends Component {
render() {
return (
<>
<MegaHeader />
<Routes>
<Route exact path="/mega" element={<Index/>}/>
<Route exact path="/mega/series" element={<Home/>}/>
<Route exact path="/mega/article-whats-new" element={<Article_New/>}/>
</Routes>
<MegaFooter />
</>
);
}
}
export default Mega_Blog
My App.js file in which I have used these both layouts based on different paths:
class App extends Component {
render() {
return (
<>
<Router >
<Routes>
<Route exact path="/" element={ <Simple_Blog />} />
<Route exact path="/mega" element={ <Mega_Blog/> } >
</Routes>
</Router>
</>
);
}
}
export default App
Can anyone please find any mistake in it or tell me some other way to do this.
Upvotes: 0
Views: 6199
Reputation: 13
I think you should better design some of your components separately for each route like the header and footer.
i.e if it is Mega_Blog then
const Mega_Blog=()=>{
return (
<Mega_Blogs_Header />
<Mega_Blog_Contents />
<Mega_Blog_Footer />
);
}
export default Mega_Blog;
Do the same thing for other routes.
Upvotes: 0
Reputation: 1078
Do this in your App.js:
<Router>
<Routes>
<Route path="/mega" element={<Mega_Blog/>}>
<Route path="/series" element={<Home/>}/>
<Route path="/article-whats-new" element={<Article_New/>}/>
<Route path="/" element={<Index/>}>
</Route>
<Route path="/simple" element={<Simple_Blog/>}>
<Route path="/article1" element={<Article1/>}/>
<Route path="/" element={<LaunchScreen/>}/>
</Route>
</Routes>
</Router>
And then modify your Mega_Blog and Simple_Blog components so that they just contain the header, the footer and an <Outlet/>
tag (for the content of the page, e.g. Article1 or LaunchScreen). For example:
<>
<MegaHeader />
<Outlet />
<MegaFooter />
</>
Upvotes: 4
Reputation: 699
use useLocation in header component and get current route and on the base of route change your header and footer.
import {
useLocation
} from "react-router-dom";
let location = useLocation();
console.log(location)
Upvotes: 2
Reputation: 593
In your header component use useLocation
from react-router-dom. Then depending on the route, you can render different header
Upvotes: 1