Published on

How to Build Simple Search Component in React

Authors

Search bar is the most important component that we would need in every projects. Lets see how to build a simple search component which you can customize it based on your needs :)

import React from 'react';
import './SearchBar.scss';
class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = { term: '' };
  }
  onInputChange(term) {
    const name = this.props.searchBoxName || undefined;
    this.setState({ term });
    if (this.props.onSearchTermChange) {
      this.props.onSearchTermChange({ name, term });
    }
  }
  render() {
    const name = this.props.searchBoxName || undefined;
    return (
      <div className="search-box">
        <div className="search-icon">
          <img src="http://share.ashiknesin.com/search-icon.png"></img>
        </div>
        <input
          name={name}
          className="search-input"
          id="search"
          type="text"
          placeholder="Search"
          value={this.state.term}
          onChange={event => this.onInputChange(event.target.value)}
          onKeyPress={this.props.onKeyPress || null}
        />
      </div>
    );
  }
}

export default SearchBar;
// SearchBar.scss
.search-box {
  background: #fbfbfb;
  border: 1px solid #eaeaea;
  border-radius: 3px;
}

.search-box {
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #f2f2f2;
  background: #fbfbfb;
  border: 1px solid #eaeaea;
  border-radius: 3px;
  height: 27px;
  margin-top: 8px;
  font-size: 14px;
  max-width: 200px;
}

.search-input {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background-color: transparent;
  border: 0px;
  padding: 5px 0px;
  font-size: 1em;
  position: relative;
  outline: 0px;
  width: 75%;
}

.search-box {
  background: #fbfbfb;
  border: 1px solid #eaeaea;
  border-radius: 3px;
}
.search-icon {
  float: left;
  color: #000;
  padding: 2px 10px;
  & img {
    width: 16px;
  }
}
import SearchBar from './SearchBar';
const ExampleComponent = props => {
  return (
    <SearchBar
      searchBoxName={'userNameSearch'}
      onSearchTermChange={this.onSearch}
    />
  );
};