How to change Header and footer of a specific webpage while using react route

Viewed 383

I am a beginner and developing a website for one of my college societies. I have 2 questions here I can develop a separate blog website but how to integrate it with the existing web app in the "/blog" route and fetch data from it and show it on the home page. I know express and mongoose but I am not sure how to implement this?

I have used react routes for ease in development and repeated header and footer. but I want to build the front end of the blog website on a different theme, same for a website of event society is going to organize. I leaving a link to its GitHub repo for reference https://github.com/SME-IIT-ISM

1 Answers

I would suggest you to check this blog post. It may solve your problem. I went through the post and the information provided there is much helpful.

  1. Creating a header and footer component

First, we need to create two new files called header.js, footer.js in our src folder or components folder.

Now inside header.js add your react app navigation links like i have shown in the below code.

  • header.js

     import React from "react";
     import { NavLink } from "react-router-dom";
    
     function Header() {
       return (
         <nav>
           <NavLink exact activeClassName="active" to="/">
             Home
           </NavLink>
           <NavLink activeClassName="active" to="/users">
             Users
           </NavLink>
           <NavLink activeClassName="active" to="/contact">
             Contact
           </NavLink>
         </nav>
       );
     }
     export default Header;
    

Next, we need to add a footer related code to footer.js file.

  1. footer.js

    import React from "react";
    function Footer() {
      return (
        <div>
          <h1>This is footer</h1>
        </div>
      );
    }
    
    export default Footer;
    
  2. Adding header and footer

Now you have successfully created two components, now you have to add a header, footer components to index.js file, so that we can see the both components on every page we navigate.

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { Route, BrowserRouter as Router, Switch } from "react-router-dom";
import App from "./App";
import Users from "./users";
import Contact from "./contact";
import Notfound from "./notfound";
import Header from "./header";
import Footer from "./footer";

const routing = (
  <Router>
    <div>
      <Header />
      <hr />
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/users" component={Users} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
      <Footer />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById("root"));
Related