7

I'm trying to set up my search so when I click enter it will begin to search and redirect to the search page. I was looking through the documentation and it wasn't clear how to set this up. How can I set up pressing enter to begin the search? I'm having a tough time figuring this out, even though I think it should be simple.

class SearchBar extends Component {
  constructor(props) {
    super(props)
    this.state = {query: '', results: [], isLoading: false}
  }

  componentWillMount() {
     this.resetComponent()
   }

   resetComponent = () => this.setState({ isLoading: false, results: [], value: '' })

   search(query) {
     this.setState({ query });
     axios
       .get(`/api/search?query=${query}`)
       .then(response => {
         console.log(query);
         this.setState({ results: response.data});
       })
       .catch(error => console.log(error));
   }


  handleSearchChange = (query) => {
    this.search(query);
    this.setState({ isLoading: true, query })

    setTimeout(() =>
      this.setState({
        isLoading: false,
      }) , 300)

  }

  handleResultSelect = (e, { result }) => this.setState({ query: result}  )

  render () {

    const resultRenderer = ({ title }) => <List content = {title}/>
    return (
      <Search
        loading={this.state.isLoading}
        onResultSelect={this.handleResultSelect}
        onSearchChange={(event) => {this.handleSearchChange(event.target.value)}}
        showNoResults={false}
        query={this.props.query}
        selectFirstResult = {true}
        resultRenderer={resultRenderer}
        results ={this.state.results}
        { ...this.props}  />

    );
  }

}


export default SearchBar

Thanks!

Alex Erling
  • 307
  • 4
  • 19

2 Answers2

4

Here is a minimal example of how you can do this.

import React from 'react'
import { Form, Input } from 'semantic-ui-react';

class FormExampleForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      query: ''
    }
  }

  handleFormSubmit = () => {
    console.log('search:', this.state.query);
  }

  handleInputChange = (e) => {
    this.setState({
      query: e.target.value
    });
  }

  render() {
    return (
      <Form onSubmit={this.handleFormSubmit}>
        <Form.Input  placeholder='Search...' value={this.state.query} onChange={this.handleInputChange} />
      </Form>
    )
  }
}

export default FormExampleForm;

Here is a working example:https://stackblitz.com/edit/react-q5wv1c?file=Hello.js

Murli Prajapati
  • 8,833
  • 5
  • 38
  • 55
-3

Modify the Search component in semantic-ui react source code to implement the onKeyPress handler

  • 4
    I think it will be better to fire an issue on their repository requesting for this modification rather than doing it yourself on the source code. – Cels Dec 03 '19 at 07:47