D
D
Dmitry2019-04-28 22:13:12
React
Dmitry, 2019-04-28 22:13:12

How to override event handler when inheriting in React?

Let's say we have a component

class Dropdown1 extends React.component {
  
  onClickHandler(e) {
    console.log(e.target.innerText)  
  }
  
  render() {
    return (
      <ul>
        {[1, 2, 3].map((number, i) => 
          <li key={i} onClick={this.onClickHandler}>{number}</li>)
        }
      </ul>
    )}
}

I want to make a child component that would
a) add to the beginning of the list b) Replace the onClickHandler handler with my own How to do this using inheritance and / or composition without changing the parent component? <li>0</li>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-04-28
@dimoff66

No need for inheritance. Make a wrapper for the main component that will pass a new handler as a parameter. And the main component will install the passed handler, or, if it does not exist, its own. For example .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question