score:0
You need to add <Switch>
as well. From the documentation:
Renders the first child or that matches the location.
<Switch>
is unique in that it renders a route exclusively. In contrast, every<Route>
that matches the location renders inclusively.
Just like the following:
<Router>
<Switch>
<Navbar isAuth={loggedIn} />
<Route exact path="/" exact component={Home} />
<Route path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
</Switch>
</Router>
Read further here: Router
I hope that helps!
score:0
Your app's state won't update if you change the value of the token
in localStorage.
You need to make sure you update the state, I've added a sandbox if it helps.
score:0
Here's how I solved this issue:
To start, I created a isLoggedIn
state in my App
class. I gave it a componentDidMount()
method that would fetch the login state from a cookie on app start. Then I created globalLogin
and globalLogout
methods as arrow functions, which set the isLoggedIn
state to true or false accordingly. I passed my Nav
component the isLoggedIn
state as a prop and passed the Login
and Nav
routes the globalLogin
and globalLogout
methods. These methods can then be called from Login
or Nav
with this.props.globalLogout();
or this.props.globalLogin();
.
This is a simplified version of my App.js
.
class App extends Component {
constructor(props){
super(props);
this.state = {
isLoggedIn: false,
}
}
componentDidMount() {
const token = Cookie.get("token") ? Cookie.get("token") : null;
if (token) {
this.setState({ "isLoggedIn": true });
}
}
globalLogin = () => {
this.setState({ "isLoggedIn": true });
}
globalLogout = () => {
this.setState({ "isLoggedIn": false });
}
render() {
return (
<Router>
<div className="App">
<Nav isLoggedIn={this.state.isLoggedIn} globalLogout={this.globalLogout}/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/login" exact>
<Login globalLogin={this.globalLogin}/>
</Route>
</Switch>
</div>
</Router>
);
}
}
EDIT: using history.push didn't work in login module above so I added an intermediate to handle props
render() {
const LoginIntermediate = (props) => {
return (
<Login {...props} globalLogin={this.globalLogin}/>
)
}
return (
<Router>
<div className="App">
<Nav isLoggedIn={this.state.isLoggedIn} globalLogout={this.globalLogout}/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/login" exact component={LoginIntermediate} />
</Switch>
</div>
</Router>
);
}
score:2
I found a simple solution: use a componentDidMount() or useEffect() function which will render automatically upon loading the NavBar page. Inside this function, use a setInterval() function to continually retrieve the auth status (say, an interval of 5000). This will continually refresh the NavBar, and change the button immediately. I imagine you would have to put the auth check in the NavBar component itself, instead of using props. I put the specific buttons I wanted to change in a separate component called NavBarUser, which changes 'login | signup' to 'logout' and contains a user avatar. I then inserted this component into the NavBar itself at the appropriate place. This is what my code looks like: ``` import React, { useState, useEffect } from 'react'; import Avatar from './Avatar'; import { BrowserRouter as Router, Link } from 'react-router-dom';
const NavBarUser = () => {
const [user, setUser] = useState({});
useEffect(() => {
{ /*
setInterval was used in order to refresh the page constantly
in order to have the "logout" button show immediately in place of
"login", as soon as user logs out.
*/}
setInterval(() => {
const userString = localStorage.getItem("user");
const user = JSON.parse(userString);
setUser(user);
}, [])
}, 5000);
const logout = () => {
return localStorage.removeItem("user");
}
if (!user) {
return (
<div className="navbar-nav ml-auto">
<Link to="/login" className="nav-item nav-link">Login</Link> <span
className="nav-item nav-link">|</span> <Link to="/SignUp" className="nav-item nav-
link">Sign Up</Link>
</div>
)
}
if (user) {
return (
<div className="navbar-nav ml-auto">
<Link to="/" className="nav-item nav-link" onClick={logout}>Logout</Link>
<Avatar img="/images/Eat-healthy.jpg" />
</div>
)
}
}
export default NavBarUser;
```
Source: stackoverflow.com
Related Query
- How to change login button to logout button in React
- React on Rails - How to change Login Link to Logout Link?
- How to hide navbar in login page in react router
- How to change text Value upon Button press in React Native?
- How to center text in Facebook Login Button for React Native (Android)?
- How to change NavBar text on login/logout in React.JS?
- How to redirect to login page on click of logout in react
- React change login link to logout after login
- React - How to change the text of accordion heading of the current clicked item
- How to change navbar background color in react when I scroll
- How to change the background and text color within button using button onClick in React JS
- how to change a text input's value in react js for array?
- How to pass props to react component to change text color
- react how to change Navbar dynamically when you are logged in
- How to individually change text color and font weight in the same div element using Tailwind CSS and React
- How to change the backgroundand text color of the navbar on scroll in react.js?
- how to change path with Link, NavLink, or Redirect (not full reload) in input navbar react
- React Native TextInput have a Default Value How can we update/pass DefualtValue as a Text entry when state change (onchangetext)
- How to change displayed text in react component?
- How to display username on navbar after login in react redux
- How can I change the color of the text separately with react hooks?
- How to change the active class in a navbar in react
- how to change default index page to login page in react js
- How to change the color of a transparent background image's text in react native?
- How to change link Navbar color while scrolling in React or Gatsby?
- How to edit a React component and change the text displayed on screen
- How to change text in text area with React Hooks?
- How to change material input text style react js
- How to hide the navbar from the login page with react router?
- How to stop the jumping jack of text change in React
More Query from same tag
- How to pass state props to another component
- Async/await inside promise
- Child Component in React (Meteor) not firing events
- I am providing a key for each child in react, but I am still getting an error?
- Is there a function to that creates a custom block inside my gutenberg block?
- Bind input field to grid component
- How to update redux store when calling a push method
- posting form data with Axios to .NET API
- Input field upon every input goes out of focus
- "Rendered more hooks than during the previous render" error when the initial value for the hook is a query result from a database
- React Bootstrap reset form after submit
- How to get the values from a Multiple Search Selection dropdown box in react-semantic-ui?
- Handling prop that may or may not contain HTML
- Which way should I import React?
- Is there a way to update history location of app registered in single spa when url changes?
- Hiding Sidebar of semantic ui react in desktop or tablet view
- Unable to login with Google OAuth when deployed to Heroku
- React: Rendering state array
- Mapping through an array using react Hooks - REFACTORING CODE
- Prevent duplicates from json array with reactjs and axios
- React hook - `useEffect` with clean up
- React and Firebase - cant set the state
- Multiple calls with dependencies redux-thunk
- Sending mail with nodemailer to office@company.ro address
- Validate Select in reactjs
- Created basic JSX file to test ReactJS is not working
- Set ReactJS state asynchronously
- ReactJS : How to properly handle data fetched from food2fork API?
- Microsoft Authentication React "hash_empty_error" when using loginPopup
- React setState if Axios.get response data is good