skip to Main Content

I’m trying to conditionally switch between two HTML buttons in ReactJS based on wether the form is shown or not. Basically if the form is shown, show a submit button and if not shown, show a regular button to show the form.

This is the code that I have. (I’m using Antd’s button component but I also tried using the regular HTML button and had the same problem.

<div>
        {showForm ? (
          <Button
            loading={isUploading}
            htmlType="submit"
            form="videoForm"
            className={Styles.button}
          >
            {isUploading ? 'Uploading' : 'Upload Video'}
          </Button>
        ) : (
          <Button
            htmlType="button"
            onClick={() => setShowForm(true)}
            className={Styles.button}
          >
            {successMsg ? 'Upload Another Video' : 'Show Form'}
          </Button>
        )}
      </div>

The issue I’m having is that when the form is not shown and I click the Show Form button, the form shows correctly and the buttons switch, but the form submit event is triggering, which is not what I expected or want.

Any ideas why? And how I can fix this issue? I also tried doing the following but got the same results.

<div>
        <Button
          loading={isUploading}
          htmlType={showForm ? 'submit' : 'button'}
          form="videoForm"
          className={Styles.button}
        >
          {showForm && (isUploading ? 'Uploading' : 'Upload Video')}
          {!showForm && (successMsg ? 'Upload Another Video' : 'Show Form')}
        </Button>
      </div>

Any help would be greatly appreciated.

2

Answers


  1. try put the setShowForm in a setTimeout

    <button onClick={() => setTimeout(() => setShowForm(true))}>...</button>
    
    Login or Signup to reply.
  2. The buttons inside the form always acts as the submit button, you can prevent that by adding extra function for onClick event and preventDefault() when the button type is ‘button’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search