Reputation: 5335
In react what is the best way to create a custom event?
As an example instead of:
handleKeyPress: function(e) {
if (e.key === 'Enter') {
doSomething();
}
}
...
<input onKeyPress={this.handleKeyPress} />
It would be nice to do be able to just do:
<input onEnter={doSomething} />
Is this possible?
I could create a custom wrapper for <input>
but then what if I wanted to add it to <select>
or <textarea>
?
Upvotes: 0
Views: 2752
Reputation: 6944
I would just write a utility wrapper that takes the action as a parameter and returns the handler function:
function onEnter(action) {
return function(e) {
if (e.key === 'Enter') {
action();
}
}
}
and then import it and use it on whichever element I desired
<input onKeyPress={onEnter(doSomething)} />
Upvotes: 2
Reputation: 2851
You cannot add onEnter
or any other custom prop to standard dom elements. You can, however, wrap them in custom React components:
const MyInput = ({onEnter}) => (
<input onKeyPress={e => e.key === 'Enter' ? onEnter(e) : null } />
);
....
<MyInput onEnter={doSomething} />
Upvotes: 2
Reputation: 1681
You could create a base component that could handle all your possible events and extends that component to create custom elements, I'll say is easier this way because you will have available all your events in one class in case you need to add more or change some behaviors.
class BaseElement extends React.Component {
constructor(props){
super(props);
this.onEnter = this.onEnter.bind(this);
this.onSpace = this.onSpace.bind(this);
this.onKeyPress = this.onKeyPress.bind(this);
}
onEnter (e) {
this.props.onEnter()
}
onSpace (e) {
this.props.onSpace()
}
onKeyPress (e) {
switch(e.key){
case 'Enter':
this.onEnter()
break;
case ' ':
this.onSpace()
break;
default:
this.props.onChange()
break;
}
}
};
class CustomText extends BaseElement {
render() {
return (
<input type='text' onKeyPress={this.onKeyPress} />
)
}
};
class App extends React.Component {
render() {
return (
<CustomText onSpace={e => console.log('space')}
onEnter={e => console.log('Enter')} />
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
</head>
<body>
<div id='app'></div>
</body>
</html>
Upvotes: 2