Search code examples
javascriptreactjspreventdefault

event.preventDefault not working in React


I've followed a tutorial & they used event.preventDefault() on the Save button & save a form into the state. I've not really written the input tags yet but so far I've added the Save button and it kinda like reloads the page which it shouldn't be doing.

Here is my page component:

class manageLocationPage extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {

        };
        this.SaveLocation = this.SaveLocation.bind(this);
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    SaveLocation(event) {
        event.preventDefault();
        console.log("Saved");
    }

    render() {
        return (
            <div>
                <LocationForm listingData={this.props.listingData} onSave={this.SaveLocation}/>
            </div>
        );
    }
}

My locationForm component:

const LocationForm = ({listingData, onSave, loading, errors}) => {
    return (
        <form>
            <h1>Add / Edit Location</h1>
            <TextInput />

        {/*Here below is where we submit out input data*/}
            <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave" onClick={onSave}/>
        </form>
    );
};

Did I miss something?


Solution

  • Instead of onClick it your input.submit, you should do

    const LocationForm = ({listingData, onSave, loading, errors}) => {
        return (
            <form  onSubmit={onSave}>
                <h1>Add / Edit Location</h1>
                <TextInput />
    
            {/*Here below is where we submit out input data*/}
                <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave"/>
            </form>
        );
    };
    

    So the event is the form submission which is being prevented.

    https://facebook.github.io/react/docs/tutorial.html#submitting-the-form