React onClick works on reload but not on actual click

Viewed 817

all you need is line 13, I guess the syntax is correct but when I reload the page it's alerting 2 times without me clicking the button and then when I click it it doesn't do anything

import { useState } from 'react';
import './App.scss';
import { FullPage, Slide } from 'react-full-page';
import First from './First';

function App() {
  const [count, setCount] = useState(0);
  return (
    <FullPage controls>
      <Slide>
        <h1>Inner slide content</h1>
        <First name="Nairi" count={count} />
        <button onClick={alert()} className="btn btn-dark">+</button>
        {/* <button onClick={setCount(count - 1)} className="btn btn-dark">-</button> */}
      </Slide>
      <Slide>
        <h1>Another slide content</h1>
      </Slide>
    </FullPage>
  );
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

3 Answers

Below here ! You are immediately calling alert function as the component initially renders. That's not a right way to set a onClick in react.

<button onClick={alert()} className="btn btn-dark">+</button>

You need to do:) Since it is an alert function of javascript.

<button onClick={()=>alert()} className="btn btn-dark">+</button>

In general case, we just need to use function name without using () to set our event handler.

For example: You can create a seperate function named handleClick and cal your alert within that.

<button onClick={handleClick} className="btn btn-dark">+</button>

const handleClick = ()=>{
   alert() 
}

your syntax of writing alert is wrong correct one is this

<button onClick= {()=> alert()} className="btn btn-dark">+</button>

you need to pass a callback function not an actual function. in your code, alert function will run anytime you refresh the page and the browser reaches line 13 for compilation. you have to use onClick={alert} or onClick={() => alert()} instead.

Related