-1

Consider the app:


function App() {
  return (
      <div>
        <ComponentOne/>
        <ComponentTwo/>
      </div>
  );
}
export default App;

with ComponentTwo as:

class ComponentTwo extends React.Component{
    constructor(){
        super();
        window.handleClick = this.handleClick;
    }
    handleClick = function(){alert('hello');}
    render(){return null;}
}

Why is it that this works:

class ComponentOne extends React.Component{
    handleClick(){window.handleClick();}
    render(){return <input type="submit" onClick={this.handleClick}/>;}
}

but not this:

// no error, but does not work
class ComponentOne extends React.Component{
    render(){return <input type="submit" onClick={window.handleClick}/>;}
}

or this:

// gives an error when the "input button" is clicked saying ComponentTwo.handleClick is not a function
class ComponentOne extends React.Component{
    handleClick(){ComponentTwo.handleClick();}
    render(){return <input type="submit" onClick={this.handleClick}/>;}
}

Also in the first case, where it works, using a global (if I understand correctly) window.handleClick doesn't seem like a good practice. Is there a better way? Or, what is the "best practice" method of handling "click on one component changes the state of the other component"?

I'm not sure I am missing something - haven't done any serious JS programming; only used vanilla JS and jquery for manipulating DOM components so far. So, I'd be glad to know that as well. Thank you.

PS: I got the first method from here.

digikar
  • 576
  • 5
  • 13
  • 2
    The second non-working example doesn't work because handleClick is not a static method. You shouldn't do any of it anyway. Pass a click event to parent and back to children as props. – Roberto Zvjerković Dec 17 '19 at 14:58

1 Answers1

1

What is the "best practice" method of handling "click on one component changes the state of the other component"?

You could define the function in the parent component and pass it as a prop to any child component that will need the handler.

Or if you absolutely must define the function in the child component, you can pass it to the parent which can pass then pass it to a child component as a prop.

But it seems to me like you could do this in a better way. If you want a handler in a child component to change the state of the main component, best practice would be to lift the state.

Michael Rodriguez
  • 2,142
  • 1
  • 9
  • 15