Coder Social home page Coder Social logo

react-search's Introduction

react-search

npm version

react-search is a simple Autocomplete Search component

Install

yarn add react-search

Usage basic

Pass in your items as a prop to react-search. The items must be an array of objects with value and id, and any other props you may need, which will not be displayed. Check out the example for more info.

import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'

class TestComponent extends Component {

  HiItems(items) {
    console.log(items)
  }

  render () {
    let items = [
      { id: 0, value: 'ruby' },
      { id: 1, value: 'javascript' },
      { id: 2, value: 'lua' },
      { id: 3, value: 'go' },
      { id: 4, value: 'julia' }
    ]

    return (
      <div>
        <Search items={items} />

        <Search items={items}
                placeholder='Pick your language'
                maxSelected={3}
                multiple={true}
                onItemsChanged={this.HiItems.bind(this)} />
      </div>
    )
  }
}

ReactDOM.render( <TestComponent />, document.getElementById('root'))

Usage async

To load items async before running the search to filter results you can pass a function to the getItemsAsync prop which will be triggered to load the results each key change. An example below using the github api to search for repos. Check out the example for more info.

import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'

class TestComponent extends Component {

  constructor (props) {
    super(props)
    this.state = { repos: [] }
  }

  getItemsAsync(searchValue, cb) {
    let url = `https://api.github.com/search/repositories?q=${searchValue}&language=javascript`
    fetch(url).then( (response) => {
      return response.json();
    }).then((results) => {
      if(results.items != undefined){
        let items = results.items.map( (res, i) => { return { id: i, value: res.full_name } })
        this.setState({ repos: items })
        cb(searchValue)
      }
    });
  }

  render () {
    return (
      <div>
        <Search items={this.state.repos}
                multiple={true}
                getItemsAsync={this.getItemsAsync.bind(this)}
                onItemsChanged={this.HiItems.bind(this)} />
      </div>
    )
  }
}

ReactDOM.render( <TestComponent />, document.getElementById('root'))

Props

items (required)

List of Items to filter through, an array of items with value and id, and any other props. value is displayed. let items = [{ id: 0, value: 'ruby' }, { id: 1, value: 'lua' }

multiple (optional)

Defaults to false, set as true if you want multiple items in the list, false for a single selection dropdown.

maxSelected (optional)

Defaults to 100, a maximum number of items allowed to be selected

placeholder (optional)

placeholder for the input

NotFoundPlaceholder (optional)

The placeholder shown when no results are found

onItemsChanged (optional)

Handler returns the items from the Search autocomplete component when items are added or removed from the list.

onKeyChange (optional)

Handler returns the search value on key change.

getItemsAsync (optional)

A function to load items async before running the autocomplete filter.

Styles

Uses styled-components 💅 for the base styling.

Development

yarn
npm run dev

Build

yarn
npm run build
npm login
npm version patch
git add -A
git push origin master
npm publish

License

MIT

react-search's People

Contributors

alexesdev avatar charlieanstey avatar jameszmartin avatar navela avatar svnm avatar whoaa512 avatar yn5 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-search's Issues

Huge list of search items makes the search component hang

I have a huge list of items (over 10k) that is part of the search list. When you try to click the search, it hangs . Is there way to not show items unless a query is typed out? Or maybe a way to lazily load the items as its scrolled down.
It would be great if there is a direction that i can check.
Thanks.

Keyboard events don't change selection

Most search bars behave such that up and down arrows move through the list and the enter key triggers the search function (I think in this case it would be onItemsChanged).

Async Items

Hi!

This React components seems rather interesting!
Does it support gathering the items asynchronously from the server when the user types something?

Best regards,

Question about react-search component - message

Hi, 

I'm using the react-search component and I have a question please.
How can I change or delete this message when I want to search a name : "Please search for some items..." that red message.

Thanks a lot.

Menu doesn't disappear when it loses focus

Expected behaviour:
With the menu focussed, when the component loses focus, the menu should disappear. Effectively, the autocomplete__menu--hidden should be re-applied to the menu when the component loses focus.

Actual behaviour:
When the menu is focussed and displayed, it won't hide again regardless of losing focus or interacting elsewhere within the DOM.

Steps to reproduce:
Pretty self explanatory really, the official demo exhibits the same behaviour.

More info:
I'm using the latest version 2.0.4 via NPM, within a React 15.4.0 app. Below is the bulk of the React component I've wrapped around react-search.

search(text, cb) {
    SearchActions.searchByString(text, this.state.account.authToken);
    cb(text);
}

select(selection) {
    var result = this.state.results.find(function (result) {
        return result.id == selection[0].id;
    });
    if (result) {
        console.log(result);
        browserHistory.push(result.NodeUrl);
    }
}

render() {
    return (
        <div>
            <Search items={this.state.results}
                    placeholder='Search...'
                    multiple={false}
                    maxSelected={1}
                    getItemsAsync={this.search.bind(this)}
                    onItemsChanged={this.select.bind(this)} />
        </div>
    )
}

Mouse click vs Trackpad click

I'm having issues using the example. Selecting an item in the drop down only works when the mouse is used, not when the trackpad is used. I'm on Mac. Is anyone else facing the issue?

Access to found items and preventing display of found items

Hi,
I would like to use the items found in the search bar and send them as props to a different component. Is there anyway I can get access to the these found items.

Also, I would like to prevent displaying these items. is that possible?

Update react peer dependency to allow 0.14

Looking through you're code, I don't see any reason why someone wouldn't be able to use your module with React 0.14.

Could you please update your peer dependency range to allow for it?

Selecting input box clears text

Type something in the input box. Click away and click back in, and the input is cleared. Is this something to do with my implementation or is this the default behaviour? If the latter it should be removed and introduced as an optional setting imo.

npm install not working on 1.0.8

Hi, Sorry about opening another issue but npm install is not working on the latest version for this. this is my debug log:
Ammars-MBP:recoveryBall AmmarKarim$ npm install react-search --save

[email protected] postinstall /Users/AmmarKarim/Desktop/backUps/recoveryBall/node_modules/react-search
npm run build

[email protected] build /Users/AmmarKarim/Desktop/backUps/recoveryBall/node_modules/react-search
babel src --out-dir lib

The CLI has been moved into the package babel-cli. See http://babeljs.io/docs/usage/cli/

npm ERR! Darwin 15.0.0
npm ERR! argv "/usr/local/bin/node" "/Users/AmmarKarim/Desktop/backUps/recoveryBall/node_modules/.bin/npm" "run" "build"
npm ERR! node v5.2.0
npm ERR! npm v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: babel src --out-dir lib
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script 'babel src --out-dir lib'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the react-search package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! babel src --out-dir lib
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs react-search
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls react-search
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/AmmarKarim/Desktop/backUps/recoveryBall/node_modules/react-search/npm-debug.log
npm WARN EPACKAGEJSON [email protected] No description
npm WARN EPACKAGEJSON [email protected] No repository field.
npm ERR! Darwin 15.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "react-search" "--save"
npm ERR! node v5.2.0
npm ERR! npm v3.3.12
npm ERR! code ELIFECYCLE

npm ERR! [email protected] postinstall: npm run build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'npm run build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the react-search package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run build
npm ERR! You can get their info via:
npm ERR! npm owner ls react-search
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/AmmarKarim/Desktop/backUps/recoveryBall/npm-debug.log

non integer ID

Hello

I have long unique ID's for my items as strings, like "af0aa000-2778-11eb-9d0e-0f95b229692e"

This doesn't work with your component because of this code. (parseInt)

handleSelect(e) {

 let element = e.currentTarget.children[0]

 let item = {
  id: parseInt(element.dataset.id),
  value: element.innerHTML.replace(/&amp;/g, '&')
 }

 this.selectMenuItem(item)

}

Any possibility to change this to without parseInt?

Thx

Can't select items randomly

I'm a newbie at React so bare with me, but I got this working however I can only select items half of the time or less..

  1. I created my App using this: https://github.com/facebookincubator/create-react-app
  2. ran npm install react-search --save inside the app folder

And then added this js code to my App:

import Search from 'react-search'
import React, { Component } from 'react'
 
class App extends Component {

  HiItems(items) {
      this.setState({ repos: items })
  }

  constructor (props) {
    super(props)
    this.state = {
      repos: []
    }
  }

  getItemsAsync(searchValue, cb) {
    let url = `https://jsonplaceholder.typicode.com/todos`
    fetch(url).then( (response) => {
      return response.json();
    }).then((results) => {
      if (typeof results !== "undefined"){
        let items = results.map( (res, i) => { return { id: i, value: res.title } })
        cb(searchValue)
        this.setState({ repos: items })        
      }
    });
  }

  render () {

    return (
      <div>
        <Search items={this.state.repos} />

        <Search items={this.state.repos}
                multiple={true}
                getItemsAsync={this.getItemsAsync.bind(this)}
                onItemsChanged={this.HiItems.bind(this)} />
      </div>
    )
  }
}
export default App;

but I can only select items half of the time, here is a video of me trying to select: https://sendvid.com/emr6tqhq

I copied the css from the example folder in node_modules/react-search/example/public/react-search.css

Tested using Chrome Version 54.0.2840.98 (64-bit)

Setup default value externally

I would like to have the capability to pass a default value.
e.g. select a record from a table in a database; Click on the record, the default value in the search box will be updated from a prop or state with the option to change it using the drop down.

Bind error

I am trying the async version and and getting the following error:

Uncaught TypeError: Cannot read property 'bind' of undefined
at ./node_modules/core-js-pure/es/instance/bind.js.module.exports (bind.js:6)

Any suggestions?

`class TestComponent extends Component {
constructor(props) {
super(props);
this.state = { repos: [] };
}

getItemsAsync(searchValue, cb) {
let url = https://api.github.com/search/repositories?q=${searchValue}&language=javascript;
fetch(url)
.then(response => {
return response.json();
})
.then(results => {
if (results.items !== undefined) {
let items = results.items.map((res, i) => {
return { id: i, value: res.full_name };
});
this.setState({ repos: items });
cb(searchValue);
}
});
}

render() {
return (




);
}
}

export default TestComponent;`

Integrating with redux-form

Do you have any advice on how to use this component in conjunction with redux-form? Redux-form appears to require each custom input field to have a prop of input.value. I haven't yet worked out a way of generating that prop from the selected values. All advice/suggestions would be much appreciated. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.