John Beasley
John Beasley

Reputation: 3081

ReactJS: Form onSubmit failing to call callback

I am following a chat tutorial on YouTube found here:

https://www.youtube.com/watch?v=6vcIW0CO07k

Near the 3-4 minute mark, the tutorial begins to add onChange and onSubmit event handlers.

At this point, I should be able to click the button and an alert window should open with the input value.

Here is what I have for the UsernameForm.js file:

import React from 'react'

class UsernameForm extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        username: ''
    }

    this.onChange = this.onChange.bind(this)
    this.onSubmit = this.onSubmit.bind(this)
}

onChange(e) {
    this.setState({
        username: e.target.value,
    })
}

onSubmit(e) {
    e.preventDefault()
    this.props.onSubmit(this.state.username)
}

render () {
    return <div>
        <form>
            <input 
                type="text" 
                placeholder="What is your username?" 
                onChange={this.onChange} 
            />
            <input type="submit" />
        </form>
    </div>
  }
}

export default UsernameForm;

In the Apps.js file:

import React, { Component } from 'react'
import UsernameForm from './components/UsernameForm'

class App extends Component {
  render() {
    return <UsernameForm onSubmit={username => alert(username)} />
  }
}

export default App

Compiling is successful, but no alert window. The page just refreshes.

Does anyone see why the alert window is not firing?

Upvotes: 1

Views: 1794

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

The onSubmit callback prop that you've added needs to be invoked by the form element itself. You can do this by adding onSubmit={this.onSubmit} to the <form /> in UsernameForm:

render () {
    return <div>
        {/* form has onSubmit callback prop which is invoked when the
        form itself is submit. Wire your components onSubmit (ie 
        this.onSubmit) to the form's callback to solve the problem */}
        <form onSubmit={this.onSubmit}> 
            <input 
                type="text" 
                placeholder="What is your username?" 
                onChange={this.onChange} 
            />
            <input type="submit" />
        </form>
    </div>
  }
}

Passing this.onSubmit to the form's onSubmit callback prop causes the onSubmit() method that you've defined to be called, which in turn causes the callback passed to UsernameForm (ie where your alert is) to be invoked.

Upvotes: 3

Related Questions