React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.6/fetch-jsonp.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
SCSS
.input {
padding: 10px;
width: 250px;
border: none;
outline: none;
background-color: grey;
&::-webkit-input-placeholder { color: white; }
&:focus {
background-color: #fff;
&::-webkit-input-placeholder { color: black; }
}
}
.results {
margin: 0;
padding: 0;
top: 110px;
position: absolute;
background-color: #fff;
padding: 10px;
width: 250px;
border-top: 1px solid grey;
list-style-type: none;
}
Babel + JSX
class Search extends React.Component {
constructor() {
super();
this.state = {
searchVal: '',
results: []
}
}
handleSearchInput = async e => {
e.preventDefault();
const url = "https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrnamespace=0&exsentences=1&exintro&explaintext&exlimit=max&prop=extracts&gsrlimit=10&gsrsearch=" + e.target.value + "&format=json";
fetchJsonp(url)
.then(response => response.json())
.then(json => {
for (let item in json.query.pages) {
if (json.query.pages.hasOwnProperty(item)) {
this.state.results.push(json.query.pages[item]);
this.setState({
results: this.state.results
});
}
}
})
.catch(error => console.error(error))
this.setState({ searchVal: e.target.value });
}
handleUnfocus = () => {
this.setState({ results: [], searchVal: '' });
};
render() {
const { searchVal, results } = this.state;
const { handleSearchInput, handleUnfocus } = this;
return (
<div>
<input type="text"
className="input"
onChange={ handleSearchInput }
value={ searchVal }
onBlur={ handleUnfocus }
placeholder="Search in Wikipedia" />
{ results.length ?
<ul className="results">
{ results.map((el, idx) => {
return (
<li key={idx}>
<a href={`http://en.wikipedia.org/curid=${el.pageid}`}
className='app-post__title'
target='_blank'>{el.title}</a>
</li>
)
}) }
</ul>
:
''
}
</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<h1>Example</h1>
<Search />
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);