Reputation: 33
I am using a <ProtectedRoute/>
for components that require authentication (which works fine). Now I want to get the location before redirecting user to loginForm like this:
import React from 'react'
import auth from '../../services/authService'
import { Navigate, useLocation } from 'react-router-dom'
const ProtectedRoute = ({ children }) => {
const location = useLocation()
if (auth.getUser()) return children
return <Navigate to='/login' state={{ from: location }} replace />
}
export default ProtectedRoute
and here are the corresponding routes in App.js
<Route path='/login' element={<LoginForm />} />
<Route
path='/movies/:id'
element={
<ProtectedRoute>
<MovieForm />
</ProtectedRoute>
}
/>
and inside loginForm.jsx (which is a class component)
render() {
console.log('props', this.props)
return //...
}
but this.props in loginForm is an empty object. why? how can I access state property of <Navigate/>
now?
Upvotes: 2
Views: 3753
Reputation: 33
I only had to use location hook (useLocation) inside the loginForm.jsx (this is a class component so I had to use a trick to use hooks inside it)
import React, { Component } from 'react'
import { useLocation } from 'react-router-dom'
let location
const UseLocation = () => {
location = useLocation()
return null
}
class LoginForm extends Component {
submitForm() {
console.log('returnUrl', location.state.from.pathname)
}
render() {
return <UseLocation />
}
}
export default LoginForm
Upvotes: 1