sander
sander

Reputation: 1654

Why function inside function ReactJS?

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?

Upvotes: 0

Views: 54

Answers (2)

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190935

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.

Upvotes: 0

Related Questions