0

I have a custom component RedirectButton, which is implemented with <button> with additional routing function provided by react-router-dom V5.

The following code won't trigger the handleSubmit, why?

return <div className="import-workspace box">
        <div style={{display: "flex", flexDirection: "column"}}>
            <form ref={formRef} onSubmit={handleSubmit}>
                <h1>Import Your Space</h1>
                <InputText ref={spaceIdRef}
                           label="space-id" init={spaceId}
                           onChange={value => setSpaceId(value)}/>
                <InputText ref={mapIdRef}
                           label="map-id" init={mapId}
                           onChange={value => setMapId(value)}/>
                <InputText ref={roomsRef} area
                           label="rooms" init={rooms}
                           onChange={value => setRooms(value)}/>
                <RedirectButton text="Start Discrimination" style={{background: "lightgreen"}}
                                to="/workspace-generator"
                                formRef={formRef}/>
            </form>
        </div>
    </div>

and if I changed the <RedirectButton> to simply <button>test</button> then the handleSubmit will be called, why?


import {Link, useLocation} from "react-router-dom";


const RedirectButton = ({text, to, style, onClick}) => {
    const { pathname } = useLocation()
    const { display, justifyContent, ...rest } = style

    return <Link to={to? to: pathname}
                 onClick={onClick}
                 style={{ textDecoration: "none", display, justifyContent }}>
        <button style={{ ...rest }}>
            {text}
        </button>
    </Link>
}

export default RedirectButton
3
  • The type of the button is submit? Commented Jun 3, 2021 at 15:07
  • Please provide the code for RedirectButton Commented Jun 4, 2021 at 7:54
  • And I have discarded this way of redirecting my among pages. Now I use <Redirect to="..."> and states. Commented Jun 4, 2021 at 8:03

2 Answers 2

1

and if I changed the to simply <button>test</button> then the handleSubmit will be called, why?

By default, in browsers other than Internet Explorer, <button /> has a type of "submit" which when wrapped inside a <form /> element will submit the form.

The following code won't trigger the handleSubmit, why?

The parent <Link /> component intercepts the mouse or keyboard event and prevents the event propagating down to the <button /> element

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

Comments

0

Try adding type="submit" to the <button> element:

<button style={{ ...rest }} type="submit">
   {text}
</button>

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.