import { createContext, useState } from "react";
import {BrowserRouter, Route, Routes, Link} from "react-router-dom"
import Dashboard from "./dashboard";
import Loginpage from "./loginpage";
import Profilepage from "./Profilepage";
export const userContext = createContext();
function App(){
const [name, setName] = useState("")
return(
<>
<userContext.Provider value = {{name, setName}}>
<BrowserRouter>
<Link to="/">profilepage</Link>
<Link to="/dashboard">Dashboard</Link>
<Link to="/loginpage">Loginpage</Link>
<Routes>
<Route path="/" element={<Profilepage/>}/>
<Route path="/dashboard" element={<Dashboard/>}/>
<Route path="/loginpage" element={<Loginpage/>}/>
</Routes>
</BrowserRouter>
</userContext.Provider>
</>
)
}
export default App;
This is App component connect here we will assign the path through the route and create Link, to go another component, it is the replacement of tag, userContext is used to share the data components together easily, it is the solution of props drilling also,
First we create use navigate and we put it that in variable , that variable is userContext at the same time we should export it, then we create a function App() after that function we should export that function, because after export only we can able to connect component together,
Link only present in inside the BrowserRouter.
then create variable through the useState inside the App function
then we write return () , return only able to keep only one div, so w should create one div and we put these in it. inside return we should provide .
import { useContext } from "react";
import { userContext } from "./App";
import { useNavigate } from "react-router-dom";
function Loginpage(){
const {setName} = useContext(userContext);
const navigate = useNavigate();
function handleClick(){
navigate("/dashboard")
}
return(
<>
<h1>Login page</h1>
<input type="text" placeholder="entername" onChange={(e) => setName(e.target.value )} />
<button onClick={handleClick}>login</button>
</>)
}
export default Loginpage;
import { useContext } from "react";
import { userContext } from "./App";
import { useNavigate } from "react-router-dom";
import Profilepage from "./Profilepage";
function Dashboard(){
const {name} = useContext(userContext);
const navigate = useNavigate();
function logout(){
navigate("/")
}
return(
<>
<h1>Dash Board</h1>
<h2>welcome {name}</h2>
<button onClick={logout}>logout</button>
</>
);
}
export default Dashboard;
import { useContext } from "react";
import { userContext } from "./App";
function Profilepage(){
const { name } = useContext(userContext);
return (
<div>
<h1>Profile Page</h1>
<h2>User Name : {name}</h2>
</div>
);
}
export default Profilepage;
Top comments (0)