Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Joshua Rajandiran Avatar asked Oct 15 '25 15:10

Joshua Rajandiran


1 Answers

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

like image 186
garajo Avatar answered Oct 18 '25 06:10

garajo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!