1

I'm trying to wrap a react-router Link in a submit button. I know there is this option: Wrapping a react-router link in an html button but it doesn't handle the submit itself.

I have something like this in mind:

<button type='submit'>
  <Link to={{pathname : "/user/signup", search:"?page=sectionTwo"}} >
    CONTINUE
  </Link>  
</button>

The Form itself is handled by Formik, if that helps.

ChronicLogic
  • 313
  • 3
  • 17
  • Why do you want to do that? Wat do you want to achieve? Nesting links inside buttons is asking for trouble. – Thijs Kramer Nov 09 '18 at 19:17
  • well, the overall goal is to have three children on separate pages that have an animation transition when the user completes the form and clicks continue. This changes the url, so that the user can go back to the previous form using "back" browser button and the info written there is not lost. I wrapped the children in `withFormik()` (formik npm) and `withRouter()`. The parent has a `BrowserRouter` rendering the children, and I manage to pass the child values to the url (`location.state`) but I can't extract it since it doesn'y re-render on url update. sigh :) sorry... I'm a little out of it – ChronicLogic Nov 09 '18 at 21:31

2 Answers2

3

I am assuming you have

<form onSubmit={someFunction}> 
// Your submit button somewhere here
</form> 

And you want to redirect user to a different page when the user clicks the submit button. I would approach it this way,

constructor(props) {
    super(props);
    this.state = { redirect: false }
}

handleSubmit() {
    // do some check before setting redirect to true
    this.setState({ redirect: true });
}

render() {
    // you could reset the this.state.redirect to false here before redirecting a user
    if (this.state.redirect) return <Redirect to='some url' />;
    else return (
         <div>
             <form onSubmit={this.handleSubmit.bind(this)}>
                 <button type='submit'> Continue </button>
             </form>
         </div>
    )
}

Idea is when the user clicks submit, it updates state, re-renders the component and see if redirect is true, if so it will redirect the user to the page. I think it is awkward to wrap Link that is not supposed to work as a button -IMO.

Junhouse
  • 41
  • 4
  • Yeah, I agree for the link inside the button, I just have a very strange set up to work with, and I'm not sure what to do. My children are wrapped in two HOC's and need to share form data between each other while leaving a browser history behind and get animated on transitions. It's a bit of a pain hehe – ChronicLogic Nov 09 '18 at 21:22
0

Create onSubmit handler and inside create a transition to another page:

onSubmit = (value) => {
  const { history } = props;
  history.push('your link');
}

And do not have to use it Link component

Vasyl Nahuliak
  • 1,912
  • 2
  • 14
  • 32