Reputation: 1296
I am using Github Search API for people to be able to search for repositories on github. I'm using React and am quite new to all of this. I want to pass the input value to the AJAX request so it only requests that repository with the specific name. Is there a way to use React to pass the input value?
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.onKeyUp = this.onKeyUp.bind(this);
this.onChange = this.onChange.bind(this);
}
render() {
return(
<form>
<input type="text" className="searchbox" onChange={this.onChange} onKeyUp={this.onKeyUp} />
<ul className="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form>
);
}
onChange(event) {
const matchArray = findMatches(this.value, repositories);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, "gi");
const cityName = place.city.replace(regex, `<span className="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span className="hl">${this.value}</span>`);
return `
<li>
<span className="name">${cityName}, ${stateName}</span>
</li>
`;
}).join('');
console.log(matchArray);
}
onKeyUp(event) {
const matchArray = findMatches(this.value, repositories);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, "gi");
const cityName = place.name.replace(regex, `<span className="hl">${this.value}</span>`);
return `
<li>
<span class="nameName">${cityName}, </span>
</li>
`;
}).join('');
console.log(matchArray);
}
}
ReactDOM.render(
<SearchBox />,
document.getElementById("searching")
);
JS
const endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm;
const repositories = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => repositories.push(...data));
function findMatches(wordToMatch, repositories) {
return repositories.filter(place => {
const regex = new RegExp(wordToMatch, "gi");
return place.city.match(regex) || place.state.match(regex);
});
};
So as you can see I want to pass the input value into a variable called searchTerm.
Upvotes: 1
Views: 1317
Reputation: 6507
You can add ref
attribute to a DOM element you would like to get reference to. Then you can refer to that element in your react component.
In your case you can add ref
to the search box as follows
<input type="text" ref={(input) => { this.searchBox = input; }} className="searchbox" ... />
and then refer to it's value in your react component as this.searchBox.value
.
Beart in mind that if you are using react state to manage your app's state you will need to put your fetch request in the component. If you do not want to do this I suggest you to look at Flux or Redux for your app's state management.
Edit
Based on your comment I created a codepen to illustrate how one could refer to the value of the input field using a ref
attribute http://codepen.io/DeividasK/pen/PpZpNL.
Upvotes: 1