S. Schenk S. Schenk - 11 months ago 76
React JSX Question

Stop button nested inside a form from submitting and have it fire a different function

I have a close button nested inside a form that is supposed to reset the form and close the popup modal the form is sitting on.

I've changed the button type from the default submit to type='reset' and have an onClick that is supposed to fire my resetting/closing function, but the function is never being called and instead the submit function is called.

is that not possible with jsx or what am I missing?

(Note that Button is just a component wrapping a

<button>
html tag)

import Button from '../../../components/Button'

export const SomeForm = (props) => (
<form className='quote-form__wrapper' onSubmit={props.onSubmit}>
<Button
className='close-btn'
type='reset'
onClick={props.resetForm}
value='CLOSE' text='x' />

some form fields...

<Button
className='btn ripple-btn'
type='submit'
text={props.btnText} />
</form>
)


EDIT:

I should add that when I don't use a custom Button component to render the button element it does work even though I don't change the button type the right function (resetForm) is being called:

const someForm = (props) => (
<form onSubmit={props.onSubmit}>
<div>
<button className='close-btn' onClick={props.resetForm} value='CLOSE'>
x
</button>

some form fields...

<button
className='ripple-btn btn'
type='submit'>
{props.btnText}
</button>
</div>
</form>
)


For what it's worth the Button component looks like this:

const Button = (props) => (
<button className={props.className} {...props.attributes}>
{props.text}
</button>
)

export default Button

Answer Source

You aren't passing down the other props properly in your Button component. You should use {...props} and not {...props.attributes}.

const Button = (props) => (
  <button className={props.className} {...props}>
    {props.text}
  </button>
);

export default Button;

Any props that you don't want to pass directly to the button could be obtained from the props using object destructuring:

const Button = ({text, className, ...props}) => (
  <button className={className} {...props}>
    {text}
  </button>
);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download