I get a username from "login.jsx" and i want to pass it to the "App.js" to access in everywhere. How can I do that?
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
}, []);
return (
<BrowserRouter>
<Offer/>
<Navigationbar/>
<Route path="login" element={user ? <Navigate to="/courses" /> : <Login />} />
</Routes>
<Footer />
</BrowserRouter>
);
}
CodePudding user response:
you can pass callback function to Login component as props and call this prop inside Login component and pass user name as argument, then inside callback function you call setUser function to update the value of user
function App() {
const [user, setUser] = useState(null);
const updateUser = (value) => {
setUser(value);
}
useEffect(() => {
}, []);
return (
<BrowserRouter>
<Offer/>
<Navigationbar/>
<Route path="login" element={user ? <Navigate to="/courses" /> : <Login updateUser={updateUser} />} />
</Routes>
<Footer />
</BrowserRouter>
);
}
CodePudding user response:
Here is How you can do that
App.jsx
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
}, []);
const updateUser = (newUser) => {
setUser(newUser);
}
return (
<BrowserRouter>
<Offer/>
<Navigationbar/>
<Route path="login" element={user ? <Navigate to="/courses" /> : <Login onNewUser={updateUser} />} />
</Routes>
<Footer />
</BrowserRouter>
);
}
In Login.jsx when you get new user call props.updateUser(user)
CodePudding user response:
You can do that with React Context;
Basically, contexts are global states. You can read more here : https://reactjs.org/docs/context.html
It allows you to wrap your <App />
into a context provider and pass to your wrapper a value that you will be able to user in your App.