I'm a React newbie, and I'm trying to figure out how to add functions conditionally to an element. In jquery, I might have the following code.
<div class="editor-container">
<textarea id='editor'></textarea>
</div>
$(function(){
$(document).on("keyup", "#editor", function () {
// do something on editor keyup
});
});
But at a later date I could drop in another js file with this code
$(function(){
$(document).on("keyup", "#editor", function () {
// do something additionally on editor keyup
});
});
I can't figure out how to do this in React.
import React from 'react';
export default class Editor extends React.Component {
handleTextChange(e) {
// do stuff with content
}
render() {
return (
<div className="editor-container">
<textarea
onChange={this.handleTextChange}>
</textarea>
</div>
);
}
}
As far as I can see, whatever I want to happen onChange
I need to declare in advance. How do I add some kind of behaviour to a component after the fact?
update
I guess I didn't explain myself very well, so let me give a more general explanation of what I'd like to do.
My app will have an Editor
component, but the editor is likely to have a ton of different features triggered from the keyup / keydown / change events. For instance, I'd like to have key sounds - when the user types, they'll get typewriter noises. However, I don't want to embed all the code for loading and playing sound files in the Editor
component. I'd like to separate all that out to another file.
I'm guessing the simple answer is that I would put this in an invisible KeyDown
component nestled within Editor
, like so:
<div class="editor-container">
<textarea id='editor'></textarea>
<KeySounds />
</div>
But I'm not sure how to tie these other components into the keydown events - maybe I should be using some kind of event emitter?