I have learned the basics of ReactJS, and now I want to try it out what I have learned. Therefore I am building this small application to put my learning into practice. I have added below two images. Where I have several buttons in my Home view (1st image). And when buttons are clicked I would like to go to a different view (the 2nd image) where it has a different layout.
I want to know whether this is achievable through ReactJS.
I have used react-router-dom, but what it does is it adds the content of the button 1 view to the end of the home page view. Below is the code I have used.
App.js
import './App.css';
import 'bootstrap/dist/css/bootstrap.css'
import HomePage from './components/HomePage';
function App() {
return (
<div className="container-fluid vh-100">
<HomePage />
</div>
);
}
export default App;
HomePage View
import { useNavigate, Route, Routes } from "react-router-dom";
import Service1 from './Service1';
function HomePage() {
const navigate = useNavigate();
const navigateToService1 = () => {
navigate('/service1');
}
return (
<div className="row">
<div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 vh-100 bg-danger">
</div>
<div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 vh-100 bg-warning">
<button className="btn btn-lg btn-success" onClick={navigateToService1}>Service1</button>
</div>
<Routes>
<Route path="/service1" element={<Service1 />}></Route>
</Routes>
</div>
)
}
export default HomePage;
Below is the Button 1 view (or the service 1 view in here)
function Service1() {
return (
<div className="row">
<div className="col-12">
<h1>This is Service1</h1>
</div>
</div>
);
}
export default Service1;
>Solution :
The code currently is unconditionally rendering the HomePage component, and then all the routes below it. Move the routes into App and render HomePage also on its own route.
App
function App() {
return (
<div className="container-fluid vh-100">
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/service1" element={<Service1 />} />
</Routes>
</div>
);
}
HomePage
function HomePage() {
const navigate = useNavigate();
const navigateToService1 = () => {
navigate('/service1');
};
return (
<div className="row">
<div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 vh-100 bg-danger">
</div>
<div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 vh-100 bg-warning">
<button
className="btn btn-lg btn-success"
onClick={navigateToService1}
>
Service1
</button>
</div>
</div>
);
}

