0

This is the answer to one of my react course's problem.

import React from 'react';
const useState = React.useState;

export default function App() {
    const [count, setCount] = useState(0);
    
    const onButtonClick = () => {
        setCount(count+1);
    };
    
    return (
        <div>
            <button onClick={onButtonClick}>Click Me!</button>
            
            <h1>Current Count: {count}</h1>
        </div>
    );
}

In react, why does it cause error when you do put argument in onButtonClick function.

    const onButtonClick = (count) => {
        setCount(count+1);
    };

Shouldn't we need to put count as argument in order to use it into function? What am I getting wrong?

1 Answer 1

1

The error is caused since the callback will try to add a Number with an Object. The first argument in your event callback is the SyntheticEvent Object. If you want to make your callback accept an argument, you should rewrite your JSX like so:

<button onClick={(event) => onButtonClick(event, count)}>Click Me!</button>

In your event callback you can use this argument like this:

const onButtonClick = (event, count) => {
  setCount(count+1);
};

The above is not needed since the function is inside the local scope of your functional component. This means it can access the count variable, unlike many other programming languages.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.