Page keeps Refreshing on Button Click – React JS Fix

The default behavior of a button inside the form is to submit the data. Hence, it keeps refreshing in our React application and our onClick function doesn’t work normally. We can fix this issue by preventing the default behavior of the button and adding our custom logic to be executed on the onClick event. Let’s pick an example.

import React from 'react';

const App = () => {
    const clickHandle = () => {
        console.log('You clicked the button')
    }
    return (
        <form>
            <button onClick={clickHandle}>Click Me</button>
        </form>
    );
}

export default App;

Since the button is inside the form tag, clicking on it may refresh the page. You can fix this by adding event.preventDefault() in our clickHandle. I have given the full code below.

import React from 'react';

const App = () => {
    const clickHandle = event => {
        event.preventDefault()
        console.log('You clicked the button')
    }
    return (
        <form>
            <button onClick={clickHandle}>Click Me</button>
        </form>
    );
}

export default App;

Now, it doesn’t reload the page and your logic inside the clickHandle works normally.

One Comment on “Page keeps Refreshing on Button Click – React JS Fix”

Leave a Reply