0

There's this piece of code in ReactJS documentation:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Why for example the same thing couldn't be done like this:

function handleClick(){
    console.log("The component was clicked");
}

function Component(props){
    return <a href="#">Click me</a>
}



ReactDOM.render(<Component onClick={handleClick}/>, document.getElementById('root'));

Can someone help me understand why there has to be two functions or point me in a direction where this would be explained to a beginner?

2 Answers 2

1

The second version is not going to work because onClick on Component will be interpreted as a prop and not an event handler. You could fix it like this:

function handleClick(){
    console.log("The component was clicked");
}

function Component(props){
    return <a href="#" onClick={handlerClick}>Click me</a>
}

ReactDOM.render(<Component />, document.getElementById('root'));

Now, why not use two functions instead of one main with handler inside? Well you can but this version lacks code encapsulation. ActionLink in your first version is a concrete unit that embodies everything it needs while in the second snippet, Component is basically useless without additional handleClick function.

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

4 Comments

Ohhh right, so when you pass anything to a component, it is a prop.
Yes, that's right. Plus in React 16 component can return multiple elements without common wrapper. So whatever you define on component is a prop.
What does that handleClick(e) mean? I know that e stands for event, but I'm not passing any arguments to it?
This is event object. Event handler handleClick is called with this parameter. onClick={handleClick} it means that you pass reference to the function as event handler. React will call this function with event object as a parameter when event occures.
0

ActionLink is a component/class type. It allows for encapsulation and code reuse of all of the behavior needed for that link. If it was a free function, it would loose that OO design tenant.

1 Comment

It's a component? They didn't say it in the docs and I'm having hard time understanding this, what about the handleClick(e), I know the (e) stands for event but how does it exactly work since it is never passed as an argument to the handleclick(e) function?

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.