3

I have a React component with a form that has an action like so:

<center>
    <Form
        action={`/api/sets/`}
        method="post"
        onSubmit={this.onSubmit}>

        <Button color="primary" type="submit">
            Finish
        </Button>
    </Form>
</center >

The onSubmit function looks like this:

onSubmit = (e) => {
    e.preventDefault()
    window.location = "/workout-history";
    e.target.submit()
}

The action to /api/sets/ happens after clicking the button and the onSubmit function does get called but the page isn't redirected. In the post to /api/sets I am returning status 204 so that shouldn't determine where it goes. I am guessing it's possible the function gets called first then the action gets called. Any ideas on how to call the forms action and redirect the page elsewhere?

1
  • if you want to form does the action why do you have e.preventDefault() Commented Jan 21, 2019 at 13:59

2 Answers 2

2

You can use import react-router-dom for redirecting.

import { Redirect } from 'react-router-dom'


onSubmit = () => {
      return <Redirect to='/target' />
  }

you can view more in : https://medium.com/@anneeb/redirecting-in-react-4de5e517354a

Sign up to request clarification or add additional context in comments.

2 Comments

That's still not working. It's doing the exact same thing. The function gets called but the page doesn't redirect. I'm not sure why.
Can you try change your button finish ? with : <input type="submit" value="Submit" />
0

The answer you are looking for is probably this.

Prefer using withRouter HOC and call history.push('/new-location') in onSubmit function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.