score:2
you don't need to use the link component in this example. try using the history prop (props.history.push('/')) see the below examples, the last one should apply to you:
in your app.js router:
<switch>
<route path="/auth" component={auth} />
<route path="/errorpage" component={errorpage} />
<route path="/" exact component={homescreen} />
<redirect to='/' />
</switch>
on the page where you want to redirect:
import react, { usestate } from 'react'
const auth = props => {
const [form, setform] = usestate({
data: {
email: '',
password: ''
}
})
const authhandler = async (event) => {
event.preventdefault()
try {
// await dispatch(action) // dispatch to redux or send a fetch
props.history.push('/') // redirects if no errors
} catch (err) {
props.history.push('/errorpage') // redirects if an error
}
}
const inputchangedhandler = e => {
setform({
...form,
data: {
...form.data,
[e.target.id]: e.target.value
}
})
}
return (
<div>
<form onsubmit={authhandler}>
<input id='email' type='email' value={form.data.email} onchange={inputchangedhandler} />
<input id='password' type='password' value={form.data.password} onchange={inputchangedhandler} />
<button type='submit'>login</button>
</form>
</div>
)
}
export default auth
in your case try the below if the page is on the route stack the history prop will be available or you will have to use withrouter or usehistory hook to get access to the history prop.
const clickhandler = () => {
try {
// await dispatch(action)
props.history.push('/') // redirects
} catch (err) {
props.history.push('/errorpage') // redirects
}
}
return (<button type='button' onclick={clickhandler}>click me</button)
score:0
you can use "redirect" from "react-router-dom"
example:
import { redirect } from "react-router-dom";
<link to='/upload'>
<button
variant="contained"
color="primary"
onclick={async () => {
await verificationp(phone, code).then(async (result) => {
if ((await result) === true) {
//i want to redirect to another page
return <redirect to="your_url" />
} else {
//i want to display an alert
}
});
}}
>
submit
</button>
</link>
score:0
i tend to use the state system (redux) to resolve this issue.
so my problem was i wanted to fire an event.preventdefault() to stop a link being clicked, but then i wanted to do an api call after it (to check login status, as it was a complex iot device) and click the link if the check was fine, but not click the link if it wasn't. however, the event.preventdefault() stopped me doing this, because it cancels any events (i'm sure there are nicer ways to achieve this! but time targets and all that).
i solved this by:
- having my usual async function with the event.preventdefault() inside it.
- within the first call i set some state in redux, just a basic boolean.
- if the api check was successful then i call the same click function again (using .click()) and bypass the event.preventdefault() thanks to redux (then reset the state afterwards) which forces the re-direct. if the check failed then i display an error message and don't display again (while obviously updating redux).
the state management system inside react is very powerful. you can do some hacky things! but sometimes the other "correct" solutions don't work for you; for example the history props functionality, which you can get round that other ways via state management.
score:2
here is the redirect doc
i think best thing you can do is create a separate function for onclick and change a state to redirect, so this way you can prevent some action by user while request is in progress
const [redirectto, setredirectto] = usestate('');
const chekcfromserver = async () => {
await verificationp(phone, code).then(async (result) => {
if ((await result) === true) {
setredirectto('/somewhereinyour/application')
} else {
// i want to display an alert
}
});
};
and when in render
return (
<>
redirectto && <redirect to={{pathname: redirectto }} />
...rest of your code
</>
)
Source: stackoverflow.com
Related Query
- Redirect to another page in reactJS onClick
- How to redirect to another page on button click in Reactjs
- How to Redirect to another page in ReactJS when a IF condition is executed?
- onClick post request and redirect to another page
- How could i use the routing in reactjs to redirect from one page after loading to another url
- How do I redirect after login to another page in ReactJs
- How to redirect to another page and use props in reactjs
- ReactJS - How to redirect another page using history.push by passing data?
- How to redirect to another page in reactjs
- How to redirect to another Page using a button in Reactjs
- Form Fails to redirect to another page upon submission - ReactJS
- Redirect to another page in reactjs not working
- React - How can I redirect to another page after some conditions are met on the OnClick of a Button?
- Programatically redirect user to another page ReactJS
- Cannot redirect one page to another page in ReactJs
- How can I redirect user to another page when he clicks on alert box in Reactjs
- How to redirect to another page when the current page is refreshed Reactjs
- react button onClick redirect page
- Next.js Redirect from / to another page
- How to redirect to a gatsby-react page with an onclick event of a component?
- I want to redirect my reactjs page to regular .html page?
- Redirect to error page ReactJS and react-router
- How to go to another page onClick in react
- How to call another component from onClick function in ReactJS
- How to make a button redirect to another page in React
- How to redirect one page to another page in reactJS?
- ReactJS onclick add or remove class to another element
- How can I redirect all clients to another page with socket.io?
- How do I test next/link (Nextjs) getting page redirect after onClick in React?
- How do I redirect user to another page after submit the form?
More Query from same tag
- Dynamic Background Image React
- How to extract props and states from one sibling component to another with react hooks?
- How to convert image source into a JavaScript File object
- How to add the camera on a web application in react.js?
- React: Passing react-icon through an Dictionary?
- Nextjs: How to use ContextAPI with multiple values all of which need to be updated from child components
- webpack 4 react unexpected token ...(spread operator)
- Navigating from App.js to Places.js
- How to refer to `defaultProps` inside `defaultProps`?
- How to pass data from a table row and pass it to another component when it renders?
- How to show multiple loading Skeleton screen on looping array in react using material ui Skeleton component?
- React Redux dispatch function: Expected 0 arguments, but got 1 TS2554
- React router briefly shows the login screen and then redirects to dashboard if user is logged in
- React Map function not rendering on browser, but it is console.logging
- Hover event does not target children
- Structuring Normalized JSON response in Redux store and mapping to React component props
- Keep getter function in sync with an object's current state in React/TypeScript
- redux-simple-router - perform action based on URL
- How to redraw text rendered using SVGRenderer in Highcharts React?
- How to define variables in JSX
- Typescript custom @types package for @types/react-router
- Using a ref to get a size of a functional react component
- Somehow getting updated state in reducer
- state props overridden by plugin props
- React routing issue with hashHistory push
- Users visits not being sent to my Analytics account
- Recommended ways to build a responsive table
- Render map not displaying data on screen
- Regular expression to determine if phone number starts with a zero
- Single line subobject check