crazy4groovy
2/7/2018 - 2:33 AM

Native CSS search engine - jets.js.org

Native CSS search engine - jets.js.org

/**
 * Inspired by: https://jets.js.org
 **/
import React from 'react'
import PropTypes from 'prop-types'

const style = Object.freeze({
  borderRadius: '5px',
  padding: '.1em'
})

const filteringStyle = Object.freeze({
  backgroundColor: 'lightyellow',
  border: '2px solid yellow'
})

class Jets extends React.Component {
  static propTypes = {
    attr: PropTypes.string,
    filteringStyle: PropTypes.object,
    placeholder: PropTypes.string,
    selector: PropTypes.string,
    style: PropTypes.object
  }

  static defaultProps = {
    attr: 'jets',
    filteringStyle,
    placeholder: 'Search...',
    selector: '.jets-item',
    style
  }

  state = {
    filterBy: ''
  }

  render() {
    const { filterBy } = this.state
    const {
      attr,
      filteringStyle,
      placeholder,
      selector,
      style
    } = this.props

    const cssStyle = filterBy
      ? `${selector}:not([data-${attr} *= "${filterBy.toLowerCase()}"]) { display: none }`
      : ''

    return (
      <span>
        <input
          type="text"
          value={filterBy}
          placeholder={placeholder}
          onChange={({ target }) => this.setState({ filterBy: target.value })}
          onKeyDown={({ keyCode }) => (keyCode === 27) && this.setState({ filterBy: '' })}
          style={Object.assign({}, style, filterBy && filteringStyle)}
        />
        <style>{cssStyle}</style>
      </span>
    )
  }
}

export default Jets