article

Monday, August 30, 2021

ReactJS - Autocomplete Json data

ReactJS - Autocomplete Json data

Autocomplete allows users to have other suggested strings or values displayed on typing of the relevant text in the input field.
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
 
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS - Autocomplete</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
import json from './data/results.json';

class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = { suggestions:[] };
		this.search = this.search.bind(this);
	}
	
	search(event) {
		let input = event.target.value;
		//console.log('event.target.value: ' + input);
		console.log('this.searchResults: ' + json);
		let matches = [], i;
		
		if (input.length > 1) {
			for (i = 0; i < json.length; i++) {
				if (json[i].match(input)) {
					matches.push(json[i]);
				}
			}
		}
		
		this.setState({ suggestions: matches });
	}

	render() {
		return (
			<div>
        <h2>ReactJS - Autocomplete</h2>
				<label>Search Here</label>  <input onKeyUp={this.search.bind(this)}/> 
				<React.Fragment>
					<ul style={{listStyleType:'none'}}>
						{this.state.suggestions.map(res => (
							<li key={res}>
								{res}
							</li>
						))}
					</ul>
				</React.Fragment>
			</div>
		);
	}
}

export default App; 
src/data/results.json
[
	"Leanne Graham",
	"Ervin Howell",
	"Clementine Bauch",
	"Patricia Lebsack",
	"Chelsey Dietrich",
	"Mrs. Dennis Schulist",
	"Kurtis Weissnat",
	"Nicholas Runolfsdotti",
	"Glenna Reichert",
	"Clementina DuBuque",
	"Airi Satou",
	"Angelica Ramos",
	"Ashton Cox",
	"Bradley Greer",
	"Brenden Wagner",
	"Brielle Williamson",
	"Bruno Nash",
	"Caesar Vance",
	"Cara Stevens"
] 

Related Post