score:2
why not recompose your route element to have private routers and public routes? private routes will be those requiring authentication and public once will not require it. when someone tries to access a private route without authentication, they will automatically be sent away.
create an element called privateroute
and put your firebase auth inside it. example:
const privateroute = ({children, ...props}) => {
const auth = firebase.auth();
const [user, setuser] = usestate(null);
useeffect(()=>{
auth.onauthstatechanged(()=> {
setuser(auth.currentuser);
})
}, []);
return (
<route {...props} render={() => {
return valid === null ?
<div>some kind of loader/spinner here...</div>
:
user ?
children
:
<redirect to='/login' />
}} />
)
}
then in your app
, use it like so:
return (
<browserrouter>
<switch>
<privateroute exact path="/">
<homepage />
</privateroute>
<route exact path="/login" component={loginpage} />
</switch>
</browserrouter>
);
this will redirect anybody trying to access /
to /login
if they are not authenticated.
later any route you create can be wrapped like this if it requires authentication.
score:0
i am using the following approach and it works fine (just copy my existing project that works):
import react, {usestate, useeffect} from 'react'
import {browserrouter as router, switch, route, redirect} from "react-router-dom"
import {connect} from "react-redux"
import useauth from './hooks/useauth'
import styles from './styles.js'
import landing from './components/landing'
import login from './components/login'
import logout from './components/logout'
import post from './components/post'
import users from './components/users'
import user from './components/user'
import signup from './components/signup'
import profile from './components/profile'
import addsocieta from './components/addsocieta'
import constructor from './components/constructor'
const mapstatetoprops = state => ({
...state
});
function connectedapp() {
const [dimension, setdimention] = usestate({windowwidth: 0, windowheight: 0})
const currentstyles = {
...styles,
showfootermenutext: styles.showfootermenutext(dimension),
showsidebar: styles.showsidebar(dimension),
topmenucollapsed: styles.topmenucollapsed(dimension),
topmenuheight: styles.topmenuheight(dimension),
paddingleftright: styles.paddingleftright(dimension),
fullscreenmenufontsize: styles.fullscreenmenufontsize(dimension),
showsublogotext: styles.showsublogotext(dimension),
roundedimagesize: styles.roundedimagesize(dimension)
};
const [auth, profile] = useauth()
const [isloggedin, setisloggedin] = usestate(false)
useeffect(() => {
if (auth && auth.uid) {
setisloggedin(true)
} else {
setisloggedin(false)
}
updatedimensions();
window.addeventlistener("resize", updatedimensions);
return function cleanup() {
window.removeeventlistener("resize", updatedimensions);
}
}, [auth, profile]);
function updatedimensions() {
let windowwidth = typeof window !== "undefined"
? window.innerwidth
: 0;
let windowheight = typeof window !== "undefined"
? window.innerheight
: 0;
setdimention({windowwidth, windowheight});
}
return (<router>
<redirect to="/app/gare"/>
<div classname="app">
<switch>
<route path="/constructor"><constructor styles={currentstyles}/></route>
<route path="/post"><post/></route>
<route path="/login"><login styles={currentstyles}/></route>
<route path="/logout"><logout styles={currentstyles}/></route>
<route path="/users"><users styles={currentstyles}/></route>
<route path="/user/:uid"><user styles={currentstyles}/></route>
<route path="/app"><landing styles={currentstyles}/></route>
<route path="/signup" render={isloggedin
? () => <redirect to="/app/gare"/>
: () => <signup styles={currentstyles}/>}/>
<route path="/profile" render={isloggedin
? () => <profile styles={currentstyles}/>
: () => <redirect to="/login"/>}/>
<route path="/add-societa"><addsocieta styles={currentstyles}/></route>
</switch>
</div>
</router>);
}
const app = connect(mapstatetoprops)(connectedapp)
export default app;
Source: stackoverflow.com
Related Query
- How to mock history.push with the new React Router Hooks using Jest
- Firebase hosting with react router
- Using React Router with CDN and without webpack or browserify
- How can I serve robots.txt on an SPA using React with Firebase hosting?
- Managing redirects to a subdomain after authentication in a React/Rails application using React Router
- React with Firebase authentication
- Using google adsense with React + React Router
- Using Redux Form with React Router
- Refresh on protected Routes React Router with firebase auth
- Using Firebase with React in Firebase Hosting
- How to add login authentication and session to ReactJS React Router and Redux with MongoDB + NodeJS Express?
- Using render in react router dom with a private route
- Navigate to page after authentication using React Router v4
- react firebase authentication with apollo graphql
- using react router with next.js
- How to refer to data with permalinks using react router
- Send Firebase Auth user to component with React Router
- How to implement Firebase authentication with React Redux?
- Using the same component for different Routes with React Router
- Using react router with electron
- ReactJS -How to create multistep component/form with single path using React Router
- Removing Hash from react router when using with Laravel
- using React router with Next JS route
- Using if statement to determine if a Firebase User can access certain React Router paths
- Property does not exist on state - Using React Router Hooks with TypeScript
- Firebase authentication with React Redux Redux-Thunk
- How can I specify authentication globally instead of defining on every page in Next js, I am using next-auth package with react query
- How to set/access data object correctly using React with a Firebase database?
- React: Redirect to an error page with error message/stack trace using React Router
- React router using HashRoute with URL's that don't have a hash
More Query from same tag
- CSS- dropdown menu transparent background when hovering but I want an opaque color from the beginning of animation
- SetState of an array of Objects in React
- react component detect changes only after a refresh
- Video not playing on mobile using React
- Why React doesn't render my result after setState?
- How to handle keyboard events on a document level in ReacJS
- Animation not working on component in ReactJS.
- Stripe collect customer billing address and calculate tax dynamically
- Why Image attribute is not working in JSX
- Store subscribe not working in external component
- Reactjs How to use properly onKeyDownCapture?
- Conditionally change object property
- generate dates and add new property to array of object
- Grabbing data from Netlify CMS folder
- Custom Event throws TS2769: No overload matches this call
- React function Component state - Too many re-renders. React limits the number of renders to prevent an infinite loop
- react-router: get param from the router listen event fails
- Redux ConnectedProps is of type never
- React - setState pass data to updater name
- Push elements down to fill up remaining vertical space
- React JS how to interconnect input form
- Change deeply nested property on object, but with arrays mixed in
- Extending React.Component warnings
- ReactJS: Preview multiple images before upload
- how to implement addItem using react-redux
- Connected-React-Route change still causes typeError to appear
- React(nextjs) Classcomponent to function. What to do with props?
- Reveal images one by one
- Testing React Component with Enzyme and Mocha
- Accessing input value from an element using ReactJs