Routing when an input is submitted

Viewed 31

I want to route to a different path when the Save Password button(not a button) is hit. I have no idea how to implement this since I do not wanna use a link.

I use this component in my main function(app.js), but I think that I have to implement the routing here since here is also the input submit (Save Password) programmed.

Code:

import {Link, withRouter} from 'react-router-dom'

const AddPasswort = ({onChange}) => {
    const[password, setPassword] = useState('')
    const[repeatPW, setRepeatPW] = useState('')
   

   

    const onSubmit = (e) => {
        e.preventDefault();

        if(!passwort){
            alert('Please enter a new password')
            return
        
        }
        else if(passwort !== repeatPW) {
            alert('Your passwords do not match')
            return
        }
    
        onChange({passwort, repeatPW})
        
        setPassword('')
        setRepeatPW('')
    }

    return (
        <form className ='add-form' onSubmit={onSubmit} >
            <div className='form-control'>
                <label>Password</label>
                <input  type='password'
                        placeholder='Passwort...'
                        value={passwort} 
                        onChange={(e) => setPassword(e.target.value)}/>
            </div>
            <div className='form-control'>
                <label>Repeat Passwort</label>
                <input  type='password' 
                        placeholder='Repeat Password...' 
                        value={repeatPW} onChange={(e) => setRepeatPW(e.target.value)}/>
            </div>
            

            <input  type = 'submit' value = 'Save Password' className= 'btn btn-block'/>
    
        </form>
    )
}

export default withRouter(AddPasswort);```


  [1]: https://i.stack.imgur.com/70LzN.jpg
  [2]: https://i.stack.imgur.com/NX5Fn.jpg
2 Answers

You can use the history object from react-router to redirect the user to another route by using history.push(path). The also have a useHistory hook you can use if you prefer using hooks in this situation.

Hope this was helpful.

First you need to import useHistory() hook from react-router-dom then do this:

import {Link, withRouter} from 'react-router-dom'
const AddPasswort = ({onChange}) => {
    const[password, setPassword] = useState('')
    const[repeatPW, setRepeatPW] = useState('') 
    // create a history object 
    const history = useHistory()  
    const onSubmit = (e) => {
        e.preventDefault();

        if(!passwort){
            alert('Please enter a new password')
            return
        
        }
        else if(passwort !== repeatPW) {
            alert('Your passwords do not match')
            return
        }
    
        onChange({passwort, repeatPW})
        
        setPassword('')
        setRepeatPW('') 
        // navigate to where you want 
        history.push("/your_path")
    }

Good luck letvme know if it works

Related