So I want whenever the user presses on the contact text on my NavBar component to redirect the user in the HomePage to the specific Component Contact. I tried using Router DOM to redirect user to the component but it removes the rest of page and has only the component, I want to remain in the same home page.
Using Vite + React and tailwind
App.jsx
type hereimport React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import NavBar from './components/NavBar';
import Hero from './components/Hero';
import Mission from './components/Mission';
import Contact from './components/Contact';
import Footer from './components/Footer';
import Home from './pages/Home';
import ProfilePage from './pages/ProfilePage';
import SettingsPage from './pages/SettingsPage'
import CommingSoon from './pages/ComingSoon';
function App() {
return (
<Router>
<div>
<NavBar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/SettingsPage" element={<SettingsPage />} />
<Route path="/Profile" element={<ProfilePage />} /> {/* Add this line for the new page */}
<Route path="/CommingSoon" element={<CommingSoon />} />
</Routes>
<Footer />
</div>
</Router>
)
}
export default App
HomePage.jsx
import React from 'react';
import Hero from '../components/Hero';
import Mission from '../components/Mission';
import Contact from '../components/Contact';
import TestComp from '../components/TestComp';
const Home = () => {
return (
<>
{/* Output goes here */}
<Hero />
<Mission />
<TestComp />
<Contact /> {/* This text on navbar*/}
</>
);
};
export default Home;
…………………………………………………………………….
NavBar.jsx
// src/components/NavBar.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const NavBar = () => {
return (
<nav className="bg-gray-800 p-4">
<div className="container mx-auto flex items-center justify-between px-10">
<div className="text-white font-bold text-lg"><Link to={"/CommingSoon"}>Akadimia</Link></div>
<ul className="flex space-x-5">
<li className="text-white"><Link to="/">Home</Link></li>
<li className="text-white"><Link to="/SettingsPage">Contact</Link></li> {/* This text on navbar*/}
<li className="text-white"><Link to="/Profile">Profile</Link></li>
</ul>
</div>
</nav>
);
};
export default NavBar;
I tried using Router dom to redirect user to the component but it removes the rest of page and has only the component, I want to remain in the same home page.
2
Answers
You can add an ID to the container of the component, e.g.:
Then you can link to this element by redirecting to "/#contact"
You can try this code after updating NavBar.jsx and Home.jsx so when the "Contact" link is clicked, it will smoothly scroll to the Contact section on the Home page instead of navigating to a separate page.
Navbar.jsx:-
Home.jsx:-