Protect routes react router dom 6 - reactjs

I have a route ('profile/edit') that edits some information, and I want to prevent the user from reaching it by typing in the URL. For example, I want if the user types www.mywebsite.com/profile/edit/ in the URL, it will get redirected to www.mywebsite.com/. So I only want it to be accessible when you click the edit button. How do I do this? I'm using react route 6 for this project.

Is this URL accessible only if logged in?
Or do you need any param values to edit?
If yes, please double check your implementation, there you have other best methods to do it
Answer
Call a useNavigate in one of your root component (inside useEffect which only call once)
//rootComponent
const navigate = useNavigate()
useEffect(()=> {
navigate('/')
), [])
//Rest of your code

Related

Pass onclick function to component using react router

I'm (obviously) fairly new to ReactJS. I'm using Router v6 for navigation between pages. I have a case where the action of a button on Component A must depend on which component (B or C or ...) launched the page. But, using useNavigate, it doesn't seem to be possible to send a function to the target component A, only text fields seem to be allowed in the object. That is, the following doesn't work:
let navigate = useNavigate()
function nextClick() {
navigate('/UserProfile', {state:{
okClick: userProfileOkClick,
cancelClick: backButtonClick
}})
}
That is, I want to navigate to the UserProfile component, and pass the callback functions its buttons should use. It doesn't work -- in the UserProfile page, the state object is null.
So is there a way to navigate to a new page and dynamically change the button callbacks? I hope so...
Thanks!

Automatically try to sign in on initial page load using React, ideas on how to do that?

trying to use Microsoft's SSO with React, and I want to
on first load to activate the method to attempt to sign in. So that I don't need to ask the user to click a button, it should just be automatic.
I'm new to react and lifecycle methods, but it doesn't make sense to use componentWillLoad or componentDidLoad because it would just be checking everytime. Basically the whole site should be only viewable if logged in, so I believe setting up my protected paths after this should be doable
Any ideas on how to attempt this?
Edit:
useEffect = () => {
!this.props.account ? this.props.onSignIn() : <AuthWrapper/>
}, [];
You can use the useEffect hook in react and pass in an empty dependency so that the effect is only called once on initial page load. The same thing could be done with componentDidMount. You could put a function within the hook or lifecycle method to check if the user is logged in then show different pages based on if that value. Something like this:
useEffect(() => {
// check here if user is logged in
loggedIn ? showPageA : showPageB
}, []);

How to prevent to visit login page if user is logged in

How can I prevent to visit login page if user is logged in, I don't want to show user login page if user if user is not logged out. but I have tried with few step but it is not working for me.
I am storing static value in localstorage and if user try to come back into page login page then there I have created a function that user can visit to login page or not
login.js
componentWillMount(){
var id = localstorage.getitem('id')
if(id == "1"){
return <Redirect to="/dashboard"/>
}
}
Here I am able to get it and it going inside if condition as well but not redirecting to dashboard
I don't know what I am doing wrong here.
Your help would be highly appreciated
Thanks in Advance
Redirect works only when it is rendered, which means it is inside render or one of the functions called by it.
Returning a Redirect inside componentDidMount does not redirect the user. For use inside componentDidMount, you can use the imperative API:
this.props.history.push("/dashboard");
Docs for history
Note that this works only if the component is directly rendered inside a Route, otherwise props history will not be present. In other case, you can use withRouter higher order component.

Modal behavior back/forward button using react-router 4

I have a React app using React Router 4. A login modal is used to authenticate users. In order to support the UX requirements I've been given, I need to have the back button close the modal.
I was able to accomplish a login modal that supports this using a simple push state:
const {history,location} = this.props
const nextState = {showLogin: true}
history.push({...location, state: {...location.state, ...nextState}})
The behavior works as expected. HOWEVER… it would be ideal if pressing the forward button did not reopen the modal.
I don't see a way to pop a location off history with react router. But what I'd like to do is listen to route changes and if the location.state changes back to the showLogin modal being falsey, but the location is the same, it pops the previous location off history.
Use history.replace('') instead of history.push('') while going back.This way, the existing login route, will get replaced from the history stack

React Router Dom Prevent Prompt When Params Change

I am building a React Redux application and I am using <Prompt/> from react-router-dom to prevent a user from navigating away from a page when a specific icon is being rendered on the page.
It works fine except for when the params in the url change and then it fires the <Prompt/> when I don't want it to fire because I haven't actually tried to navigate anywhere. My url looks like:
http://localhost:8080/#/path/im/on?ids=1%2C24&from=1512518400000&searchRequest=e0007&to=1512604799000
When the ids in the url become successful, they are removed from the url but <Prompt/> is still fired.
Is there any way I can prevent <Prompt/> from firing when the url params change and the first part of the url stays the same? i.e. http://localhost:8080/#/path/im/on
Not sure if this is still relevant to you but you can do the following:
'message' prop in the Prompt component can either be a string or a function that returns a string or boolean.
<Prompt
message={(location) => {
return location.pathname.startsWith("your url")
? true
: `Are you sure you want to go to ${location.pathname}?`
}}
/>
if a function is passed to message prop then it will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
here is the documentation link: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Prompt.md

Resources