Skip to content

Commit

Permalink
[fixed] SafeAnchor event ordering
Browse files Browse the repository at this point in the history
If we prevent default before applying the `onClick` function provided in
props then we prevent elements from using the `event.preventDefault()`
mechanics for anchors as buttons. For example in the Dropdown re-work
this prevented me from having the Dropdown work when in a Nav since the
toggle is an anchor. Yet that functionality should allow uses to prevent
the Dropdown if they want in their own `onClick` handler. This will
enable such a use case.
  • Loading branch information
mtscout6 committed Jun 10, 2015
1 parent 704a168 commit 598b9d8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
7 changes: 2 additions & 5 deletions src/SafeAnchor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import createChainedFunction from './utils/createChainedFunction';

/**
* Note: This is intended as a stop-gap for accessibility concerns that the
Expand All @@ -16,17 +17,13 @@ export default class SafeAnchor extends React.Component {
if (this.props.href === undefined) {
event.preventDefault();
}

if (this.props.onClick) {
this.props.onClick(event);
}
}

render() {
return (
<a role={this.props.href ? undefined : 'button'}
{...this.props}
onClick={this.handleClick}
onClick={createChainedFunction(this.props.onClick, this.handleClick)}
href={this.props.href || ''}/>
);
}
Expand Down
16 changes: 12 additions & 4 deletions test/SafeAnchorSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,12 @@ describe('SafeAnchor', function() {

it('prevents default when no href is provided', function(done) {
const handleClick = (event) => {
event.defaultPrevented.should.be.true;
done();
expect(event.isDefaultPrevented()).to.not.be.ok;

setTimeout(() => {
event.isDefaultPrevented().should.be.true;
done();
}, 100);
};
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor onClick={handleClick} />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
Expand All @@ -54,8 +58,12 @@ describe('SafeAnchor', function() {

it('does not prevent default when href is provided', function(done) {
const handleClick = (event) => {
expect(event.defaultPrevented).to.not.be.ok;
done();
expect(event.isDefaultPrevented()).to.not.be.ok;

setTimeout(() => {
expect(event.isDefaultPrevented()).to.not.be.ok;
done();
});
};
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='#' onClick={handleClick} />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
Expand Down

0 comments on commit 598b9d8

Please sign in to comment.