Reputation: 5685
How should I structure this ReactJS code to use ReactDOM / getDOMNode()
instead of jQuery. This plays a sound when a button is pressed.
Not sure if I should put the .play()
in myAudioObject
and access it via Refs, or the other way... pass Refs with .getDomNode()
into myPlayButton
.
Also, is using jQuery they way i have it below considered bad practice with ReactJS?
var myAudioObject = React.createClass({
render: function() {
return (
<audio id="mySoundClip" preload="auto">
<source src='audio/thing.mp3'></source>
Your browser does not support audio.
</audio>
);
}
});
var myPlayButton = React.createClass({
handleClickPlay: function() {
var audio = $("#mySoundClip")[0];
audio.load(); // This reloads the audio tag in the DOM, so also reloads ReactJS component.
audio.play();
},
render: function() {
return (
<button onClick={this.handleClickPlay}>Play</button>
);
}
});
var App = React.createClass({
render: function() {
return (
<div>
<myAudioObject />
<myPlayButton />
</div>
);
}
});
React.renderComponent((
<App />
), document.body);
Upvotes: 7
Views: 10297
Reputation: 9859
You're on the right track, try using refs like this (or use flux) - JSFiddle
var myAudioObject = React.createClass({
play: function () {
var audio = this.getDOMNode();
audio.load();
audio.play();
},
render: function() {
return (
<audio preload="auto">
<source src='audio/thing.mp3'></source>
Your browser does not support audio.
</audio>
);
}
});
var myPlayButton = React.createClass({
render: function() {
return (
<button onClick={this.props.handleClickPlay}>Play</button>
);
}
});
var App = React.createClass({
handleClickPlay: function() {
this.refs.audioObject.play()
},
render: function() {
return (
<div>
<myAudioObject ref="audioObject" />
<myPlayButton handleClickPlay={this.handleClickPlay} />
</div>
);
}
});
using jQuery like that is frowned upon, because it quickly becomes unclear whats depending on what.
Upvotes: 7