-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRouter.jsx
More file actions
70 lines (61 loc) · 1.51 KB
/
Router.jsx
File metadata and controls
70 lines (61 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Router.jsx
import React from 'react';
import { BrowserRouter, Routes, Route, useNavigate } from 'react-router-dom';
/*
✅ React Router Overview:
- BrowserRouter: Top-level component that enables routing using the browser history.
- Routes: Wrapper for <Route> components.
- Route: Defines a path and the component to render.
- useNavigate: Hook to programmatically navigate between routes.
*/
// 🟢 Home Page Component
const Home = () => {
const navigate = useNavigate();
const goToForm = () => {
navigate('/form');
};
return (
<div>
<h1>Home Page</h1>
<button onClick={goToForm}>Go to Form</button>
</div>
);
};
// 🟢 Form Page (Controlled Component)
const FormPage = () => {
const [name, setName] = React.useState('');
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted name: ${name}`);
navigate('/');
};
return (
<div>
<h1>Form Page</h1>
<form onSubmit={handleSubmit}>
<label>
Name:{' '}
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
);
};
// 🔁 Router Setup
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/form" element={<FormPage />} />
</Routes>
</BrowserRouter>
);
};
export default Router;