Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onClick works on reload but not on actual click

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>
like image 740
Altro Avatar asked Nov 19 '25 23:11

Altro


2 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() 
}
like image 195
Imran Rafiq Rather Avatar answered Nov 22 '25 11:11

Imran Rafiq Rather


your syntax of writing alert is wrong correct one is this

<button onClick= {()=> alert()} className="btn btn-dark">+</button>
like image 35
Sanoodia Avatar answered Nov 22 '25 13:11

Sanoodia