Reputation: 109
I am currently hacking around with a small front-end react project that is hitting Soundcloud's API. Very basic as of right now, I'm just taking in some user input and querying the api endpoint for related songs. For some strange reason I cannot get the enter key to submit my form and thus fire my this.handleSubmit() method. The only way I can get it to fire is to click the button my enter functionality seems to be broken. I searched around and can't find what I'm overlooking, any assistance is greatly appreciated!
import React from 'react';
import Styles from '../styles/index.js'
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.initPlayer(this.props.song)
};
initPlayer(song){
SC.oEmbed(song, { auto_play: true }).then(function(song) {
document.getElementById('player').innerHTML = song.html;
});
}
handleSubmit(e){
e.preventDefault();
let term = document.getElementById('search').value
SC.get('/tracks', {
q: term
})
.then( (tracks) => {
const song = tracks[0].permalink_url;
if (tracks.length < 1) {
alert('not found!');
}
SC.oEmbed(song, { auto_play: true }).then(function(song) {
document.getElementById('player').innerHTML = song.html;
});
document.getElementById('search').value = '';
});
}
render() {
return (
<div>
<div className="col-lg-12">
<div style={Styles.playerStyle} id="player"></div>
<label htmlFor="search">Artist:</label>
<input type="text" className="form-control" id="search" />
<div className="text-center">
<form onSubmit={this.handleSubmit}>
<button type='submit' style={Styles.buttonStyle} className="btn btn-primary">Submit</button>
</form>
</div>
<div id="player"></div>
<br />
</div>
</div>
);
}
}
export default SearchBar;
Upvotes: 4
Views: 2876
Reputation: 185
form can only be submitted by enter-key when it is focus and has input|button(type="submit"). So just move input into your form.
<form onSubmit={this.handleSubmit}>
<input type="text" className="form-control" id="search" />
<button type='submit' style={Styles.buttonStyle} className="btn btn-primary">Submit</button>
</form>
Upvotes: 4