Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
import React, { Component } from 'react'; import axios from 'axios'; export default class App extends Component { state = { searchValue: '', options: [], showOptions: false, roots: [], } componentDidMount () { axios.get(`https://swapi.co/api/`) .then(data => { var arr = []; for (var key in data.data) { arr.push(data.data[key]); } this.setState({ roots: arr }); }) .catch(err => console.log('Error: ', err)); } onSearchChange = event => { this.setState({ searchValue: event.target.value }); if (event.target.value.length >= 3) { this.setState({ options: [], showOptions: true }); this.state.roots.map((root) => { axios.get(`${root}?search=${this.state.searchValue}`) .then(data => { data.data.results.map((item) => { const rootName = root.split('/'); const searchItem = { name: item.name, rootName: rootName[4], } this.setState(prevState => ({ options: [...prevState.options, searchItem] })) }); }) .catch(err => console.log('Error: ', err)); }) } else { this.setState({ showOptions: false }); } } render() { return ( <div> <input value={this.state.searchValue} onChange={this.onSearchChange} /> { this.state.showOptions ? <div className="options__list"> { this.state.options.map( (item, index) => { return ( <div key={ index } className="options__item" > <span className="options__text"> {item.name} - {item.rootName} </span> </div> ); } ) } </div> : null } </div> ) } }