0

I am trying to to call "preventDefault" in some manner on a custom component without success. Here are my attempts. The first attempt with "e" passes the element reference and not the actual event. The second method passes the event, but the prevent default method does not prevent anything. What is the best way to do this?

<MyComponent header= {
    <div onClick={e => { e.preventDefault(); myFunction.bind(this, event) }}>
       Header
    </div> 
} />

function myFunction(event) {
   event.preventDefault();
}
3
  • Why are you passing jsx through props? Commented Oct 11, 2016 at 16:58
  • If you end doing something like this, keep looking, because there should be a better way Commented Oct 11, 2016 at 17:13
  • @notgiorgi - I am already using "Children" for another jsx property, so I did not have any other place left to pass the header jsx. Commented Oct 11, 2016 at 18:20

1 Answer 1

1

I would do it like this:

<MyComponent header={<div onClick={myFunction}>Header</div>} />

function myFunction(event) {
   event.preventDefault();
}

Or, if you need to use this in the click handler:

class App extends React.Component {
  myFunction = (event) => {
    event.preventDefault();
    this.setState({ clicked: true });
  }

  render () {
    return (
      <MyComponent header={<div onClick={this.myFunction}>Header</div>} />
    )
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

The fat arrow (=>) does this for you. But if you can't use ES6 features yet, you'd have to bind it explicitly...
@tobiasandersen - When I do it this way, a reference to the element gets passed to "myFunction", not the actual event. Is that because my function is outside the class?
No it doesn't matter. Are you doing it like this: jsfiddle.net/ybv6mtg0?
@tobiasandersen - Kind of, except I am using typescript instead of javascript.

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.